repo_name
stringlengths 7
104
| file_path
stringlengths 13
198
| context
stringlengths 67
7.15k
| import_statement
stringlengths 16
4.43k
| code
stringlengths 40
6.98k
| prompt
stringlengths 227
8.27k
| next_line
stringlengths 8
795
|
---|---|---|---|---|---|---|
osiam/auth-server | src/main/java/org/osiam/auth/configuration/OAuth2ClientCredentialsSecurity.java | // Path: src/main/java/org/osiam/security/authentication/OsiamClientDetailsService.java
// @Service
// public class OsiamClientDetailsService implements ClientDetailsService {
//
// @Autowired
// private ClientRepository clientRepository;
//
// @Override
// public ClientDetails loadClientByClientId(final String clientId) {
// return clientRepository.findById(clientId);
// }
// }
| import org.springframework.security.oauth2.provider.client.ClientDetailsUserDetailsService;
import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler;
import org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.osiam.security.authentication.OsiamClientDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter; | /*
* Copyright (C) 2013 tarent AG
*
* 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 org.osiam.auth.configuration;
@Configuration
public class OAuth2ClientCredentialsSecurity extends WebSecurityConfigurerAdapter {
@Autowired | // Path: src/main/java/org/osiam/security/authentication/OsiamClientDetailsService.java
// @Service
// public class OsiamClientDetailsService implements ClientDetailsService {
//
// @Autowired
// private ClientRepository clientRepository;
//
// @Override
// public ClientDetails loadClientByClientId(final String clientId) {
// return clientRepository.findById(clientId);
// }
// }
// Path: src/main/java/org/osiam/auth/configuration/OAuth2ClientCredentialsSecurity.java
import org.springframework.security.oauth2.provider.client.ClientDetailsUserDetailsService;
import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler;
import org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.osiam.security.authentication.OsiamClientDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter;
/*
* Copyright (C) 2013 tarent AG
*
* 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 org.osiam.auth.configuration;
@Configuration
public class OAuth2ClientCredentialsSecurity extends WebSecurityConfigurerAdapter {
@Autowired | private OsiamClientDetailsService osiamClientDetailsService; |
osiam/auth-server | src/main/java/org/osiam/auth/login/ldap/OsiamLdapUserContextMapper.java | // Path: src/main/java/org/osiam/auth/configuration/LdapAuthentication.java
// @Configuration
// @ConditionalOnProperty(prefix = "org.osiam.auth-server", name = "ldap.enabled")
// public class LdapAuthentication {
//
// public static final String LDAP_PROVIDER = "ldap";
// public static final String AUTH_EXTENSION = "urn:org.osiam:scim:extensions:auth-server";
//
// @Value("${org.osiam.auth-server.ldap.server.url:}")
// private String url;
//
// @Value("${org.osiam.auth-server.ldap.server.groupsearchbase:}")
// private String groupSearchBase;
//
// @Value("#{'${org.osiam.auth-server.ldap.dn.patterns:}'.split(';')}")
// private String[] dnPatterns;
//
// @Value("${org.osiam.auth-server.ldap.mapping:}")
// private String[] attributeMapping;
//
// @Bean
// public ScimToLdapAttributeMapping ldapToScimAttributeMapping() {
// return new ScimToLdapAttributeMapping(attributeMapping);
// }
//
// @Bean
// public OsiamLdapAuthenticationProvider osiamLdapAuthenticationProvider() {
// return new OsiamLdapAuthenticationProvider(
// bindAuthenticator(),
// new DefaultLdapAuthoritiesPopulator(contextSource(), groupSearchBase),
// new OsiamLdapUserContextMapper(ldapToScimAttributeMapping()));
// }
//
// @Bean
// public BaseLdapPathContextSource contextSource() {
// return new DefaultSpringSecurityContextSource(url);
// }
//
// @Bean
// public LdapAuthenticator bindAuthenticator(){
// BindAuthenticator bindAuthenticator = new BindAuthenticator(contextSource());
// bindAuthenticator.setUserDnPatterns(dnPatterns);
// bindAuthenticator.setUserAttributes(
// Iterables.toArray(ldapToScimAttributeMapping().ldapAttributes(), String.class)
// );
// return bindAuthenticator;
// }
// }
//
// Path: src/main/java/org/osiam/auth/exception/LdapConfigurationException.java
// public class LdapConfigurationException extends AuthenticationException {
//
// public LdapConfigurationException(String s) {
// super(s);
// }
//
// public LdapConfigurationException(String s, Throwable cause) {
// super(s, cause);
// }
// }
| import com.google.common.base.Strings;
import org.osiam.auth.configuration.LdapAuthentication;
import org.osiam.auth.exception.LdapConfigurationException;
import org.osiam.resources.scim.Address;
import org.osiam.resources.scim.Email;
import org.osiam.resources.scim.Entitlement;
import org.osiam.resources.scim.Extension;
import org.osiam.resources.scim.Im;
import org.osiam.resources.scim.Name;
import org.osiam.resources.scim.PhoneNumber;
import org.osiam.resources.scim.Photo;
import org.osiam.resources.scim.Role;
import org.osiam.resources.scim.UpdateUser;
import org.osiam.resources.scim.User;
import org.osiam.resources.scim.X509Certificate;
import org.springframework.ldap.core.DirContextOperations;
import org.springframework.security.ldap.userdetails.LdapUserDetailsMapper;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID; | /*
* Copyright (C) 2013 tarent AG
*
* 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 org.osiam.auth.login.ldap;
public class OsiamLdapUserContextMapper extends LdapUserDetailsMapper {
private final ScimToLdapAttributeMapping scimLdapAttributes;
public OsiamLdapUserContextMapper(ScimToLdapAttributeMapping scimToLdapAttributeMapping) {
this.scimLdapAttributes = scimToLdapAttributeMapping;
}
public User mapUser(DirContextOperations ldapUserData) {
| // Path: src/main/java/org/osiam/auth/configuration/LdapAuthentication.java
// @Configuration
// @ConditionalOnProperty(prefix = "org.osiam.auth-server", name = "ldap.enabled")
// public class LdapAuthentication {
//
// public static final String LDAP_PROVIDER = "ldap";
// public static final String AUTH_EXTENSION = "urn:org.osiam:scim:extensions:auth-server";
//
// @Value("${org.osiam.auth-server.ldap.server.url:}")
// private String url;
//
// @Value("${org.osiam.auth-server.ldap.server.groupsearchbase:}")
// private String groupSearchBase;
//
// @Value("#{'${org.osiam.auth-server.ldap.dn.patterns:}'.split(';')}")
// private String[] dnPatterns;
//
// @Value("${org.osiam.auth-server.ldap.mapping:}")
// private String[] attributeMapping;
//
// @Bean
// public ScimToLdapAttributeMapping ldapToScimAttributeMapping() {
// return new ScimToLdapAttributeMapping(attributeMapping);
// }
//
// @Bean
// public OsiamLdapAuthenticationProvider osiamLdapAuthenticationProvider() {
// return new OsiamLdapAuthenticationProvider(
// bindAuthenticator(),
// new DefaultLdapAuthoritiesPopulator(contextSource(), groupSearchBase),
// new OsiamLdapUserContextMapper(ldapToScimAttributeMapping()));
// }
//
// @Bean
// public BaseLdapPathContextSource contextSource() {
// return new DefaultSpringSecurityContextSource(url);
// }
//
// @Bean
// public LdapAuthenticator bindAuthenticator(){
// BindAuthenticator bindAuthenticator = new BindAuthenticator(contextSource());
// bindAuthenticator.setUserDnPatterns(dnPatterns);
// bindAuthenticator.setUserAttributes(
// Iterables.toArray(ldapToScimAttributeMapping().ldapAttributes(), String.class)
// );
// return bindAuthenticator;
// }
// }
//
// Path: src/main/java/org/osiam/auth/exception/LdapConfigurationException.java
// public class LdapConfigurationException extends AuthenticationException {
//
// public LdapConfigurationException(String s) {
// super(s);
// }
//
// public LdapConfigurationException(String s, Throwable cause) {
// super(s, cause);
// }
// }
// Path: src/main/java/org/osiam/auth/login/ldap/OsiamLdapUserContextMapper.java
import com.google.common.base.Strings;
import org.osiam.auth.configuration.LdapAuthentication;
import org.osiam.auth.exception.LdapConfigurationException;
import org.osiam.resources.scim.Address;
import org.osiam.resources.scim.Email;
import org.osiam.resources.scim.Entitlement;
import org.osiam.resources.scim.Extension;
import org.osiam.resources.scim.Im;
import org.osiam.resources.scim.Name;
import org.osiam.resources.scim.PhoneNumber;
import org.osiam.resources.scim.Photo;
import org.osiam.resources.scim.Role;
import org.osiam.resources.scim.UpdateUser;
import org.osiam.resources.scim.User;
import org.osiam.resources.scim.X509Certificate;
import org.springframework.ldap.core.DirContextOperations;
import org.springframework.security.ldap.userdetails.LdapUserDetailsMapper;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
/*
* Copyright (C) 2013 tarent AG
*
* 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 org.osiam.auth.login.ldap;
public class OsiamLdapUserContextMapper extends LdapUserDetailsMapper {
private final ScimToLdapAttributeMapping scimLdapAttributes;
public OsiamLdapUserContextMapper(ScimToLdapAttributeMapping scimToLdapAttributeMapping) {
this.scimLdapAttributes = scimToLdapAttributeMapping;
}
public User mapUser(DirContextOperations ldapUserData) {
| Extension extension = new Extension.Builder(LdapAuthentication.AUTH_EXTENSION) |
osiam/auth-server | src/main/java/org/osiam/auth/login/ldap/OsiamLdapUserContextMapper.java | // Path: src/main/java/org/osiam/auth/configuration/LdapAuthentication.java
// @Configuration
// @ConditionalOnProperty(prefix = "org.osiam.auth-server", name = "ldap.enabled")
// public class LdapAuthentication {
//
// public static final String LDAP_PROVIDER = "ldap";
// public static final String AUTH_EXTENSION = "urn:org.osiam:scim:extensions:auth-server";
//
// @Value("${org.osiam.auth-server.ldap.server.url:}")
// private String url;
//
// @Value("${org.osiam.auth-server.ldap.server.groupsearchbase:}")
// private String groupSearchBase;
//
// @Value("#{'${org.osiam.auth-server.ldap.dn.patterns:}'.split(';')}")
// private String[] dnPatterns;
//
// @Value("${org.osiam.auth-server.ldap.mapping:}")
// private String[] attributeMapping;
//
// @Bean
// public ScimToLdapAttributeMapping ldapToScimAttributeMapping() {
// return new ScimToLdapAttributeMapping(attributeMapping);
// }
//
// @Bean
// public OsiamLdapAuthenticationProvider osiamLdapAuthenticationProvider() {
// return new OsiamLdapAuthenticationProvider(
// bindAuthenticator(),
// new DefaultLdapAuthoritiesPopulator(contextSource(), groupSearchBase),
// new OsiamLdapUserContextMapper(ldapToScimAttributeMapping()));
// }
//
// @Bean
// public BaseLdapPathContextSource contextSource() {
// return new DefaultSpringSecurityContextSource(url);
// }
//
// @Bean
// public LdapAuthenticator bindAuthenticator(){
// BindAuthenticator bindAuthenticator = new BindAuthenticator(contextSource());
// bindAuthenticator.setUserDnPatterns(dnPatterns);
// bindAuthenticator.setUserAttributes(
// Iterables.toArray(ldapToScimAttributeMapping().ldapAttributes(), String.class)
// );
// return bindAuthenticator;
// }
// }
//
// Path: src/main/java/org/osiam/auth/exception/LdapConfigurationException.java
// public class LdapConfigurationException extends AuthenticationException {
//
// public LdapConfigurationException(String s) {
// super(s);
// }
//
// public LdapConfigurationException(String s, Throwable cause) {
// super(s, cause);
// }
// }
| import com.google.common.base.Strings;
import org.osiam.auth.configuration.LdapAuthentication;
import org.osiam.auth.exception.LdapConfigurationException;
import org.osiam.resources.scim.Address;
import org.osiam.resources.scim.Email;
import org.osiam.resources.scim.Entitlement;
import org.osiam.resources.scim.Extension;
import org.osiam.resources.scim.Im;
import org.osiam.resources.scim.Name;
import org.osiam.resources.scim.PhoneNumber;
import org.osiam.resources.scim.Photo;
import org.osiam.resources.scim.Role;
import org.osiam.resources.scim.UpdateUser;
import org.osiam.resources.scim.User;
import org.osiam.resources.scim.X509Certificate;
import org.springframework.ldap.core.DirContextOperations;
import org.springframework.security.ldap.userdetails.LdapUserDetailsMapper;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID; | break;
case "im":
Im.Builder imBuilder = new Im.Builder().setValue(ldapValue)
.setType(new Im.Type(LdapAuthentication.LDAP_PROVIDER));
List<Im> ims = new ArrayList<>();
ims.add(imBuilder.build());
builder.addIms(ims);
break;
case "locale":
builder.setLocale(ldapValue);
break;
case "nickName":
builder.setNickName(ldapValue);
break;
case "phoneNumber":
PhoneNumber.Builder phoneNumberBuilder = new PhoneNumber.Builder().setValue(ldapValue)
.setType(new PhoneNumber.Type(LdapAuthentication.LDAP_PROVIDER));
List<PhoneNumber> phoneNumbers = new ArrayList<>();
phoneNumbers.add(phoneNumberBuilder.build());
builder.addPhoneNumbers(phoneNumbers);
break;
case "photo":
Photo.Builder photoBuilder;
try {
photoBuilder = new Photo.Builder().setValue(new URI(ldapValue))
.setType(new Photo.Type(LdapAuthentication.LDAP_PROVIDER));
List<Photo> photos = new ArrayList<>();
photos.add(photoBuilder.build());
builder.addPhotos(photos);
} catch (URISyntaxException e) { | // Path: src/main/java/org/osiam/auth/configuration/LdapAuthentication.java
// @Configuration
// @ConditionalOnProperty(prefix = "org.osiam.auth-server", name = "ldap.enabled")
// public class LdapAuthentication {
//
// public static final String LDAP_PROVIDER = "ldap";
// public static final String AUTH_EXTENSION = "urn:org.osiam:scim:extensions:auth-server";
//
// @Value("${org.osiam.auth-server.ldap.server.url:}")
// private String url;
//
// @Value("${org.osiam.auth-server.ldap.server.groupsearchbase:}")
// private String groupSearchBase;
//
// @Value("#{'${org.osiam.auth-server.ldap.dn.patterns:}'.split(';')}")
// private String[] dnPatterns;
//
// @Value("${org.osiam.auth-server.ldap.mapping:}")
// private String[] attributeMapping;
//
// @Bean
// public ScimToLdapAttributeMapping ldapToScimAttributeMapping() {
// return new ScimToLdapAttributeMapping(attributeMapping);
// }
//
// @Bean
// public OsiamLdapAuthenticationProvider osiamLdapAuthenticationProvider() {
// return new OsiamLdapAuthenticationProvider(
// bindAuthenticator(),
// new DefaultLdapAuthoritiesPopulator(contextSource(), groupSearchBase),
// new OsiamLdapUserContextMapper(ldapToScimAttributeMapping()));
// }
//
// @Bean
// public BaseLdapPathContextSource contextSource() {
// return new DefaultSpringSecurityContextSource(url);
// }
//
// @Bean
// public LdapAuthenticator bindAuthenticator(){
// BindAuthenticator bindAuthenticator = new BindAuthenticator(contextSource());
// bindAuthenticator.setUserDnPatterns(dnPatterns);
// bindAuthenticator.setUserAttributes(
// Iterables.toArray(ldapToScimAttributeMapping().ldapAttributes(), String.class)
// );
// return bindAuthenticator;
// }
// }
//
// Path: src/main/java/org/osiam/auth/exception/LdapConfigurationException.java
// public class LdapConfigurationException extends AuthenticationException {
//
// public LdapConfigurationException(String s) {
// super(s);
// }
//
// public LdapConfigurationException(String s, Throwable cause) {
// super(s, cause);
// }
// }
// Path: src/main/java/org/osiam/auth/login/ldap/OsiamLdapUserContextMapper.java
import com.google.common.base.Strings;
import org.osiam.auth.configuration.LdapAuthentication;
import org.osiam.auth.exception.LdapConfigurationException;
import org.osiam.resources.scim.Address;
import org.osiam.resources.scim.Email;
import org.osiam.resources.scim.Entitlement;
import org.osiam.resources.scim.Extension;
import org.osiam.resources.scim.Im;
import org.osiam.resources.scim.Name;
import org.osiam.resources.scim.PhoneNumber;
import org.osiam.resources.scim.Photo;
import org.osiam.resources.scim.Role;
import org.osiam.resources.scim.UpdateUser;
import org.osiam.resources.scim.User;
import org.osiam.resources.scim.X509Certificate;
import org.springframework.ldap.core.DirContextOperations;
import org.springframework.security.ldap.userdetails.LdapUserDetailsMapper;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
break;
case "im":
Im.Builder imBuilder = new Im.Builder().setValue(ldapValue)
.setType(new Im.Type(LdapAuthentication.LDAP_PROVIDER));
List<Im> ims = new ArrayList<>();
ims.add(imBuilder.build());
builder.addIms(ims);
break;
case "locale":
builder.setLocale(ldapValue);
break;
case "nickName":
builder.setNickName(ldapValue);
break;
case "phoneNumber":
PhoneNumber.Builder phoneNumberBuilder = new PhoneNumber.Builder().setValue(ldapValue)
.setType(new PhoneNumber.Type(LdapAuthentication.LDAP_PROVIDER));
List<PhoneNumber> phoneNumbers = new ArrayList<>();
phoneNumbers.add(phoneNumberBuilder.build());
builder.addPhoneNumbers(phoneNumbers);
break;
case "photo":
Photo.Builder photoBuilder;
try {
photoBuilder = new Photo.Builder().setValue(new URI(ldapValue))
.setType(new Photo.Type(LdapAuthentication.LDAP_PROVIDER));
List<Photo> photos = new ArrayList<>();
photos.add(photoBuilder.build());
builder.addPhotos(photos);
} catch (URISyntaxException e) { | throw new LdapConfigurationException("Could not map the ldap attibute '" |
rampage128/hombot-control | mobile/src/main/java/de/jlab/android/hombot/data/BotCursorAdapter.java | // Path: common/src/main/java/de/jlab/android/hombot/common/data/HombotDataContract.java
// public class HombotDataContract {
// // To prevent someone from accidentally instantiating the contract class,
// // give it an empty constructor.
// public HombotDataContract() {}
//
// /* Inner class that defines the table contents */
// public static abstract class BotEntry implements BaseColumns {
// public static final String TABLE_NAME = "bot";
// public static final String COLUMN_NAME_NAME = "name";
// public static final String COLUMN_NAME_ADDRESS = "address";
// }
// }
| import android.content.Context;
import android.database.Cursor;
import android.support.v4.widget.CursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import de.jlab.android.hombot.R;
import de.jlab.android.hombot.common.data.HombotDataContract; | package de.jlab.android.hombot.data;
/**
* Created by frede_000 on 08.10.2015.
*/
public class BotCursorAdapter extends CursorAdapter {
static class ViewHolder {
TextView name;
TextView address;
ImageView delete;
}
private View.OnClickListener mSecondaryClickListener;
public BotCursorAdapter(Context context, Cursor cursor) {
super(context, cursor, 0);
}
// The newView method is used to inflate a new view and return it,
// you don't bind any data to the view at this point.
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View view = LayoutInflater.from(context).inflate(R.layout.listitem_bot_manager, parent, false);
ViewHolder holder = new ViewHolder();
holder.name = (TextView) view.findViewById(R.id.name);
holder.address = (TextView) view.findViewById(R.id.address);
holder.delete = (ImageView) view.findViewById(R.id.bot_delete);
holder.delete.setOnClickListener(mSecondaryClickListener);
view.setTag(holder);
return view;
}
// The bindView method is used to bind all data to a given view
// such as setting the text on a TextView.
@Override
public void bindView(View view, Context context, Cursor cursor) {
// Get ViewHolder from view to avoid findViewById calls!
ViewHolder holder = (ViewHolder)view.getTag();
// Extract properties from cursor | // Path: common/src/main/java/de/jlab/android/hombot/common/data/HombotDataContract.java
// public class HombotDataContract {
// // To prevent someone from accidentally instantiating the contract class,
// // give it an empty constructor.
// public HombotDataContract() {}
//
// /* Inner class that defines the table contents */
// public static abstract class BotEntry implements BaseColumns {
// public static final String TABLE_NAME = "bot";
// public static final String COLUMN_NAME_NAME = "name";
// public static final String COLUMN_NAME_ADDRESS = "address";
// }
// }
// Path: mobile/src/main/java/de/jlab/android/hombot/data/BotCursorAdapter.java
import android.content.Context;
import android.database.Cursor;
import android.support.v4.widget.CursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import de.jlab.android.hombot.R;
import de.jlab.android.hombot.common.data.HombotDataContract;
package de.jlab.android.hombot.data;
/**
* Created by frede_000 on 08.10.2015.
*/
public class BotCursorAdapter extends CursorAdapter {
static class ViewHolder {
TextView name;
TextView address;
ImageView delete;
}
private View.OnClickListener mSecondaryClickListener;
public BotCursorAdapter(Context context, Cursor cursor) {
super(context, cursor, 0);
}
// The newView method is used to inflate a new view and return it,
// you don't bind any data to the view at this point.
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View view = LayoutInflater.from(context).inflate(R.layout.listitem_bot_manager, parent, false);
ViewHolder holder = new ViewHolder();
holder.name = (TextView) view.findViewById(R.id.name);
holder.address = (TextView) view.findViewById(R.id.address);
holder.delete = (ImageView) view.findViewById(R.id.bot_delete);
holder.delete.setOnClickListener(mSecondaryClickListener);
view.setTag(holder);
return view;
}
// The bindView method is used to bind all data to a given view
// such as setting the text on a TextView.
@Override
public void bindView(View view, Context context, Cursor cursor) {
// Get ViewHolder from view to avoid findViewById calls!
ViewHolder holder = (ViewHolder)view.getTag();
// Extract properties from cursor | holder.name.setText(cursor.getString(cursor.getColumnIndexOrThrow(HombotDataContract.BotEntry.COLUMN_NAME_NAME))); |
rampage128/hombot-control | wear/src/main/java/de/jlab/android/hombot/data/WearBot.java | // Path: common/src/main/java/de/jlab/android/hombot/common/wear/WearMessages.java
// public final class WearMessages {
//
// public static final String MESSAGE_COMMAND = "/command";
// public static final String MESSAGE_STATUS = "/status";
// public static final String MESSAGE_CLEANDATA = "/cleandata";
// public static final String MESSAGE_MAP = "/map";
// public static final String MESSAGE_BOT_SELECT = "/bot/select";
// public static final String MESSAGE_BOT_LIST = "/bot/list";
//
// public static final String MAPENTRY_BOT_LIST = "bot_list";
// public static final String MAPENTRY_BOT_ID = "id";
// public static final String MAPENTRY_BOT_NAME = "name";
// public static final String MAPENTRY_BOT_ADDRESS = "address";
//
// public static final String CAPABILITY_HOMBOT_HOST = "hombot_host";
// public static final String CAPABILITY_HOMBOT_CLIENT = "hombot_client";
//
//
// }
| import com.google.android.gms.wearable.DataMap;
import de.jlab.android.hombot.common.wear.WearMessages; | package de.jlab.android.hombot.data;
/**
* Created by frede_000 on 15.10.2015.
*/
public class WearBot {
private long id;
private String address;
private String name;
public WearBot(DataMap botMap) { | // Path: common/src/main/java/de/jlab/android/hombot/common/wear/WearMessages.java
// public final class WearMessages {
//
// public static final String MESSAGE_COMMAND = "/command";
// public static final String MESSAGE_STATUS = "/status";
// public static final String MESSAGE_CLEANDATA = "/cleandata";
// public static final String MESSAGE_MAP = "/map";
// public static final String MESSAGE_BOT_SELECT = "/bot/select";
// public static final String MESSAGE_BOT_LIST = "/bot/list";
//
// public static final String MAPENTRY_BOT_LIST = "bot_list";
// public static final String MAPENTRY_BOT_ID = "id";
// public static final String MAPENTRY_BOT_NAME = "name";
// public static final String MAPENTRY_BOT_ADDRESS = "address";
//
// public static final String CAPABILITY_HOMBOT_HOST = "hombot_host";
// public static final String CAPABILITY_HOMBOT_CLIENT = "hombot_client";
//
//
// }
// Path: wear/src/main/java/de/jlab/android/hombot/data/WearBot.java
import com.google.android.gms.wearable.DataMap;
import de.jlab.android.hombot.common.wear.WearMessages;
package de.jlab.android.hombot.data;
/**
* Created by frede_000 on 15.10.2015.
*/
public class WearBot {
private long id;
private String address;
private String name;
public WearBot(DataMap botMap) { | this.id = botMap.getLong(WearMessages.MAPENTRY_BOT_ID); |
sdnwiselab/sdn-wise-java | ctrl/src/main/java/com/github/sdnwiselab/sdnwise/adapter/AbstractAdapter.java | // Path: ctrl/src/main/java/com/github/sdnwiselab/sdnwise/controlplane/ControlPlaneLogger.java
// public final class ControlPlaneLogger {
//
// /**
// * Private constructor.
// */
// private ControlPlaneLogger() {
// // Nothing to do here
// }
//
// /**
// * Creates a logger using the SimplerFormatter formatter.
// *
// * @param prefix the name of the ControlPlane class
// */
// public static void setupLogger(final String prefix) {
//
// Logger logger = Logger.getLogger(prefix);
// logger.setUseParentHandlers(false);
// SimplerFormatter f = new SimplerFormatter(prefix);
// StreamHandler h = new StreamHandler(System.out, f) {
// @Override
// public synchronized void publish(final LogRecord record) {
// super.publish(record);
// flush();
// }
// };
// logger.addHandler(h);
// }
// }
| import com.github.sdnwiselab.sdnwise.controlplane.ControlPlaneLogger;
import java.util.Observable;
import java.util.Observer;
import java.util.logging.Level;
import java.util.logging.Logger;
| /*
* Copyright (C) 2015 SDN-WISE
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.sdnwiselab.sdnwise.adapter;
/**
* Representation of an abstract adapter. It is an observable class for the
* adaptation, but it is also an observer for changes coming from the specific
* adapter type.
*
* @author Sebastiano Milardo
*/
public abstract class AbstractAdapter extends Observable implements Observer {
/**
* Logger.
*/
protected static final Logger LOGGER = Logger.getLogger("ADP");
private boolean active;
/**
* Creates an AbstractAdapter.
*/
AbstractAdapter() {
this.active = false;
| // Path: ctrl/src/main/java/com/github/sdnwiselab/sdnwise/controlplane/ControlPlaneLogger.java
// public final class ControlPlaneLogger {
//
// /**
// * Private constructor.
// */
// private ControlPlaneLogger() {
// // Nothing to do here
// }
//
// /**
// * Creates a logger using the SimplerFormatter formatter.
// *
// * @param prefix the name of the ControlPlane class
// */
// public static void setupLogger(final String prefix) {
//
// Logger logger = Logger.getLogger(prefix);
// logger.setUseParentHandlers(false);
// SimplerFormatter f = new SimplerFormatter(prefix);
// StreamHandler h = new StreamHandler(System.out, f) {
// @Override
// public synchronized void publish(final LogRecord record) {
// super.publish(record);
// flush();
// }
// };
// logger.addHandler(h);
// }
// }
// Path: ctrl/src/main/java/com/github/sdnwiselab/sdnwise/adapter/AbstractAdapter.java
import com.github.sdnwiselab.sdnwise.controlplane.ControlPlaneLogger;
import java.util.Observable;
import java.util.Observer;
import java.util.logging.Level;
import java.util.logging.Logger;
/*
* Copyright (C) 2015 SDN-WISE
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.sdnwiselab.sdnwise.adapter;
/**
* Representation of an abstract adapter. It is an observable class for the
* adaptation, but it is also an observer for changes coming from the specific
* adapter type.
*
* @author Sebastiano Milardo
*/
public abstract class AbstractAdapter extends Observable implements Observer {
/**
* Logger.
*/
protected static final Logger LOGGER = Logger.getLogger("ADP");
private boolean active;
/**
* Creates an AbstractAdapter.
*/
AbstractAdapter() {
this.active = false;
| ControlPlaneLogger.setupLogger("ADP");
|
sdnwiselab/sdn-wise-java | ctrl/src/main/java/com/github/sdnwiselab/sdnwise/controlplane/ControlPlaneLogger.java | // Path: core/src/main/java/com/github/sdnwiselab/sdnwise/util/SimplerFormatter.java
// public class SimplerFormatter extends Formatter {
//
// /**
// * The format of the date in the log messages.
// */
// private final SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
// /**
// * The name of the layer writing the log.
// */
// private final String name;
//
// /**
// * Creates a SimplerFormatter given a n. The n is used in the log to
// * identify the writer of the message.
// *
// * @param n the n of layer that creates the log. It is appended in the log
// * message
// */
// public SimplerFormatter(final String n) {
// name = n;
// }
//
// @Override
// public final String format(final LogRecord record) {
// StringBuilder sb = new StringBuilder(formatter
// .format(new Date(record.getMillis())));
// sb.append(" [").append(record.getLevel()).append("][").append(name)
// .append("] ").append(formatMessage(record));
//
// if (record.getThrown() != null) {
// StringWriter sw = new StringWriter();
// PrintWriter pw = new PrintWriter(sw);
// record.getThrown().printStackTrace(pw);
// sb.append(sw.toString());
// }
// return sb.append("\n").toString();
// }
// }
| import com.github.sdnwiselab.sdnwise.util.SimplerFormatter;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.logging.StreamHandler; | /*
* Copyright (C) 2016 Seby
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.sdnwiselab.sdnwise.controlplane;
/**
* Models a logger for each ControlPlane layer.
*
* @author Sebastiano Milardo
*/
public final class ControlPlaneLogger {
/**
* Private constructor.
*/
private ControlPlaneLogger() {
// Nothing to do here
}
/**
* Creates a logger using the SimplerFormatter formatter.
*
* @param prefix the name of the ControlPlane class
*/
public static void setupLogger(final String prefix) {
Logger logger = Logger.getLogger(prefix);
logger.setUseParentHandlers(false); | // Path: core/src/main/java/com/github/sdnwiselab/sdnwise/util/SimplerFormatter.java
// public class SimplerFormatter extends Formatter {
//
// /**
// * The format of the date in the log messages.
// */
// private final SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
// /**
// * The name of the layer writing the log.
// */
// private final String name;
//
// /**
// * Creates a SimplerFormatter given a n. The n is used in the log to
// * identify the writer of the message.
// *
// * @param n the n of layer that creates the log. It is appended in the log
// * message
// */
// public SimplerFormatter(final String n) {
// name = n;
// }
//
// @Override
// public final String format(final LogRecord record) {
// StringBuilder sb = new StringBuilder(formatter
// .format(new Date(record.getMillis())));
// sb.append(" [").append(record.getLevel()).append("][").append(name)
// .append("] ").append(formatMessage(record));
//
// if (record.getThrown() != null) {
// StringWriter sw = new StringWriter();
// PrintWriter pw = new PrintWriter(sw);
// record.getThrown().printStackTrace(pw);
// sb.append(sw.toString());
// }
// return sb.append("\n").toString();
// }
// }
// Path: ctrl/src/main/java/com/github/sdnwiselab/sdnwise/controlplane/ControlPlaneLogger.java
import com.github.sdnwiselab.sdnwise.util.SimplerFormatter;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.logging.StreamHandler;
/*
* Copyright (C) 2016 Seby
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.sdnwiselab.sdnwise.controlplane;
/**
* Models a logger for each ControlPlane layer.
*
* @author Sebastiano Milardo
*/
public final class ControlPlaneLogger {
/**
* Private constructor.
*/
private ControlPlaneLogger() {
// Nothing to do here
}
/**
* Creates a logger using the SimplerFormatter formatter.
*
* @param prefix the name of the ControlPlane class
*/
public static void setupLogger(final String prefix) {
Logger logger = Logger.getLogger(prefix);
logger.setUseParentHandlers(false); | SimplerFormatter f = new SimplerFormatter(prefix); |
sdnwiselab/sdn-wise-java | core/src/main/java/com/github/sdnwiselab/sdnwise/flowtable/ForwardBroadcastAction.java | // Path: core/src/main/java/com/github/sdnwiselab/sdnwise/util/NodeAddress.java
// public static final NodeAddress BROADCAST_ADDR = new NodeAddress("255.255");
| import static com.github.sdnwiselab.sdnwise.flowtable.AbstractAction.Action.FORWARD_B;
import static com.github.sdnwiselab.sdnwise.util.NodeAddress.BROADCAST_ADDR; | /*
* Copyright (C) 2015 SDN-WISE
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.sdnwiselab.sdnwise.flowtable;
/**
* Representation of the ForwardBroadcast action. A packet which is forwarded in
* broadcast is received by all the nodes at one hop distance.
*
* @author Sebastiano Milardo
*/
public final class ForwardBroadcastAction extends AbstractForwardAction {
/**
* Creates a ForwardBroadcast action. The next hop is set to the Broadcast
* action.
*/
public ForwardBroadcastAction() {
super(FORWARD_B); | // Path: core/src/main/java/com/github/sdnwiselab/sdnwise/util/NodeAddress.java
// public static final NodeAddress BROADCAST_ADDR = new NodeAddress("255.255");
// Path: core/src/main/java/com/github/sdnwiselab/sdnwise/flowtable/ForwardBroadcastAction.java
import static com.github.sdnwiselab.sdnwise.flowtable.AbstractAction.Action.FORWARD_B;
import static com.github.sdnwiselab.sdnwise.util.NodeAddress.BROADCAST_ADDR;
/*
* Copyright (C) 2015 SDN-WISE
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.sdnwiselab.sdnwise.flowtable;
/**
* Representation of the ForwardBroadcast action. A packet which is forwarded in
* broadcast is received by all the nodes at one hop distance.
*
* @author Sebastiano Milardo
*/
public final class ForwardBroadcastAction extends AbstractForwardAction {
/**
* Creates a ForwardBroadcast action. The next hop is set to the Broadcast
* action.
*/
public ForwardBroadcastAction() {
super(FORWARD_B); | setNextHop(BROADCAST_ADDR); |
sdnwiselab/sdn-wise-java | ctrl/src/main/java/com/github/sdnwiselab/sdnwise/adaptation/AdaptationFactory.java | // Path: ctrl/src/main/java/com/github/sdnwiselab/sdnwise/configuration/ConfigAdaptation.java
// public class ConfigAdaptation {
//
// /**
// * Contain the lower and upper adapter configurations.
// */
// private final List<Map<String, String>> lower = new LinkedList<>(),
// upper = new LinkedList<>();
//
// /**
// * Returns an unmodifiableMap containing the configurations for the lower
// * Adapter.
// *
// * @return a {@code Map<String,String>} containing the configurations for
// * the lower Adapter
// * @see com.github.sdnwiselab.sdnwise.adapter.AbstractAdapter
// */
// public final List<Map<String, String>> getLowers() {
// return Collections.unmodifiableList(lower);
// }
//
// /**
// * Returns an unmodifiableMap containing the configurations for the upper
// * Adapter.
// *
// * @return a {@code Map<String,String>} containing the configurations for
// * the upper Adapter
// * @see com.github.sdnwiselab.sdnwise.adapter.AbstractAdapter
// */
// public final List<Map<String, String>> getUppers() {
// return Collections.unmodifiableList(upper);
// }
//
// }
//
// Path: ctrl/src/main/java/com/github/sdnwiselab/sdnwise/configuration/Configurator.java
// public class Configurator {
//
// /**
// * Configuration parameters for the adaptation layer.
// */
// private final ConfigAdaptation adaptation = new ConfigAdaptation();
// /**
// * Configuration parameters for the controller layer.
// */
// private final ConfigController controller = new ConfigController();
// /**
// * Configuration parameters for the FlowVisor layer.
// */
// private final ConfigFlowVisor flowvisor = new ConfigFlowVisor();
//
// /**
// * Parses a file given in input containing a JSON string and returns the
// * corresponding configurator object described in the file.
// *
// * @param fileName the path to the JSON file
// * @return a configurator object
// */
// public static final Configurator load(final InputStream fileName) {
// try {
// return (new Gson()).fromJson(new JsonReader(new InputStreamReader(
// fileName, "UTF-8")), Configurator.class);
// } catch (UnsupportedEncodingException ex) {
// Logger.getLogger(Configurator.class.getName())
// .log(Level.SEVERE, null, ex);
// }
// return null;
// }
//
// /**
// * Returns a configAdaptation object.
// *
// * @return a configAdaptation object
// */
// public final ConfigAdaptation getAdaptation() {
// return adaptation;
// }
//
// /**
// * Returns a ConfigController object.
// *
// * @return a configController object
// */
// public final ConfigController getController() {
// return controller;
// }
//
// /**
// * Returns a configFlowvisor object.
// *
// * @return a configFlowvisor object
// */
// public final ConfigFlowVisor getFlowvisor() {
// return flowvisor;
// }
//
// /**
// * Returns a string representation of the object in JSON format.
// *
// * @return a JSON string representation of this object.
// */
// @Override
// public final String toString() {
// Gson gson = new GsonBuilder().setPrettyPrinting().create();
// return gson.toJson(this);
// }
//
// }
| import com.github.sdnwiselab.sdnwise.adapter.*;
import com.github.sdnwiselab.sdnwise.configuration.ConfigAdaptation;
import com.github.sdnwiselab.sdnwise.configuration.Configurator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
| /*
* Copyright (C) 2015 SDN-WISE
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.sdnwiselab.sdnwise.adaptation;
/**
* Creates an Adaptation object given the specifications contained in a
* Configurator object. This class implements the factory object pattern.
* <p>
* This class is used in the initialization phase of the network in order to
* create an adaptation object. The different types of adapter are chosen using
* the option TYPE of the configuration file provided to the ConfigAdaptation
* class.
*
* @author Sebastiano Milardo
*/
public final class AdaptationFactory {
/**
* Contains the configuration parameters of the class.
*/
private static ConfigAdaptation conf;
/**
* Returns an adaptation object given a configAdaptation object. If one of
* the adapter cannot be instantiated then this method throws an
* UnsupportedOperationException.
*
* @param c contains the configurations for the adaptation object
* @return an adaptation object
*/
| // Path: ctrl/src/main/java/com/github/sdnwiselab/sdnwise/configuration/ConfigAdaptation.java
// public class ConfigAdaptation {
//
// /**
// * Contain the lower and upper adapter configurations.
// */
// private final List<Map<String, String>> lower = new LinkedList<>(),
// upper = new LinkedList<>();
//
// /**
// * Returns an unmodifiableMap containing the configurations for the lower
// * Adapter.
// *
// * @return a {@code Map<String,String>} containing the configurations for
// * the lower Adapter
// * @see com.github.sdnwiselab.sdnwise.adapter.AbstractAdapter
// */
// public final List<Map<String, String>> getLowers() {
// return Collections.unmodifiableList(lower);
// }
//
// /**
// * Returns an unmodifiableMap containing the configurations for the upper
// * Adapter.
// *
// * @return a {@code Map<String,String>} containing the configurations for
// * the upper Adapter
// * @see com.github.sdnwiselab.sdnwise.adapter.AbstractAdapter
// */
// public final List<Map<String, String>> getUppers() {
// return Collections.unmodifiableList(upper);
// }
//
// }
//
// Path: ctrl/src/main/java/com/github/sdnwiselab/sdnwise/configuration/Configurator.java
// public class Configurator {
//
// /**
// * Configuration parameters for the adaptation layer.
// */
// private final ConfigAdaptation adaptation = new ConfigAdaptation();
// /**
// * Configuration parameters for the controller layer.
// */
// private final ConfigController controller = new ConfigController();
// /**
// * Configuration parameters for the FlowVisor layer.
// */
// private final ConfigFlowVisor flowvisor = new ConfigFlowVisor();
//
// /**
// * Parses a file given in input containing a JSON string and returns the
// * corresponding configurator object described in the file.
// *
// * @param fileName the path to the JSON file
// * @return a configurator object
// */
// public static final Configurator load(final InputStream fileName) {
// try {
// return (new Gson()).fromJson(new JsonReader(new InputStreamReader(
// fileName, "UTF-8")), Configurator.class);
// } catch (UnsupportedEncodingException ex) {
// Logger.getLogger(Configurator.class.getName())
// .log(Level.SEVERE, null, ex);
// }
// return null;
// }
//
// /**
// * Returns a configAdaptation object.
// *
// * @return a configAdaptation object
// */
// public final ConfigAdaptation getAdaptation() {
// return adaptation;
// }
//
// /**
// * Returns a ConfigController object.
// *
// * @return a configController object
// */
// public final ConfigController getController() {
// return controller;
// }
//
// /**
// * Returns a configFlowvisor object.
// *
// * @return a configFlowvisor object
// */
// public final ConfigFlowVisor getFlowvisor() {
// return flowvisor;
// }
//
// /**
// * Returns a string representation of the object in JSON format.
// *
// * @return a JSON string representation of this object.
// */
// @Override
// public final String toString() {
// Gson gson = new GsonBuilder().setPrettyPrinting().create();
// return gson.toJson(this);
// }
//
// }
// Path: ctrl/src/main/java/com/github/sdnwiselab/sdnwise/adaptation/AdaptationFactory.java
import com.github.sdnwiselab.sdnwise.adapter.*;
import com.github.sdnwiselab.sdnwise.configuration.ConfigAdaptation;
import com.github.sdnwiselab.sdnwise.configuration.Configurator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/*
* Copyright (C) 2015 SDN-WISE
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.sdnwiselab.sdnwise.adaptation;
/**
* Creates an Adaptation object given the specifications contained in a
* Configurator object. This class implements the factory object pattern.
* <p>
* This class is used in the initialization phase of the network in order to
* create an adaptation object. The different types of adapter are chosen using
* the option TYPE of the configuration file provided to the ConfigAdaptation
* class.
*
* @author Sebastiano Milardo
*/
public final class AdaptationFactory {
/**
* Contains the configuration parameters of the class.
*/
private static ConfigAdaptation conf;
/**
* Returns an adaptation object given a configAdaptation object. If one of
* the adapter cannot be instantiated then this method throws an
* UnsupportedOperationException.
*
* @param c contains the configurations for the adaptation object
* @return an adaptation object
*/
| public static Adaptation getAdaptation(final Configurator c) {
|
sdnwiselab/sdn-wise-java | core/src/main/java/com/github/sdnwiselab/sdnwise/packet/NetworkPacket.java | // Path: core/src/main/java/com/github/sdnwiselab/sdnwise/util/NodeAddress.java
// public final class NodeAddress implements Comparable<NodeAddress>, Serializable {
//
// /**
// * The default broadcast address.
// */
// public static final NodeAddress BROADCAST_ADDR = new NodeAddress("255.255");
//
// /**
// * The serialVersionUID as specified in the Serializable interface.
// */
// private static final long serialVersionUID = 1L;
//
// /**
// * A byte array containing the address. A NodeAddress is two bytes long.
// */
// private final byte[] addr = new byte[2];
//
// /**
// * Constructor method to create a Node Address from an int.
// *
// * @param a int value to set a Node Address.
// */
// public NodeAddress(final int a) {
// addr[0] = (byte) (a >>> Byte.SIZE);
// addr[1] = (byte) a;
// }
//
// /**
// *
// * Constructor method to create a Node Address from a byte array.
// *
// * @param a byte array value to set a Node Address.
// */
// public NodeAddress(final byte[] a) {
// if (a.length == 2) {
// addr[0] = a[0];
// addr[1] = a[1];
// }
// }
//
// /**
// * Constructor method to create a Node Address from a string.
// *
// * @param a string value to set a Node Address.
// */
// public NodeAddress(final String a) {
// String[] add = a.split("\\s*\\.\\s*");
// if (add.length == 2) {
// addr[0] = (byte) Integer.parseInt(add[0]);
// addr[1] = (byte) Integer.parseInt(add[1]);
// } else {
// int adr = Integer.parseInt(a);
// addr[0] = (byte) (adr >>> Byte.SIZE);
// addr[1] = (byte) adr;
// }
// }
//
// /**
// * Constructor method to create a Node Address from two int.
// *
// * @param addr0 int value to set fist part of Node Address.
// * @param addr1 int value to set second part of a Node Address.
// */
// public NodeAddress(final int addr0, final int addr1) {
// addr[0] = (byte) addr0;
// addr[1] = (byte) addr1;
// }
//
// @Override
// public int compareTo(final NodeAddress other) {
// return Integer.valueOf(intValue()).compareTo(other.intValue());
// }
//
// @Override
// public boolean equals(final Object obj) {
// return obj instanceof NodeAddress
// && ((NodeAddress) obj).intValue() == intValue();
// }
//
// /**
// * Gets the Node Address in Byte.
// *
// * @return a byte array of Node Address.
// */
// public byte[] getArray() {
// return new byte[]{addr[0], addr[1]};
// }
//
// /**
// * Gets the first Byte of a NodeAddress.
// *
// * @return a byte value of High Part of a NodeAddress.
// */
// public byte getHigh() {
// return addr[0];
// }
//
// /**
// * Gets the last Byte of a NodeAddress.
// *
// * @return a byte value of Low Part of a NodeAddress.
// */
// public byte getLow() {
// return addr[1];
// }
//
// @Override
// public int hashCode() {
// return Integer.valueOf(intValue()).hashCode();
// }
//
// /**
// * Returns the NodeAddress as an integer.
// *
// * @return int value of the NodeAddress.
// */
// public int intValue() {
// return mergeBytes(addr[0], addr[1]);
// }
//
// /**
// * Checks if the address is a broadcast address.
// *
// * @return true if equal to 255.255 false otherwise
// */
// public boolean isBroadcast() {
// return equals(BROADCAST_ADDR);
// }
//
// /**
// * Gets the Node Address in Byte.
// *
// * @return a byte array of Node Address.
// */
// public Byte[] toByteArray() {
// return new Byte[]{addr[0], addr[1]};
// }
//
// @Override
// public String toString() {
// return Byte.toUnsignedInt(addr[0]) + "." + Byte.toUnsignedInt(addr[1]);
// }
// }
| import com.github.sdnwiselab.sdnwise.util.NodeAddress;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.LinkedList;
| return "SRC";
case (TYP_INDEX):
return "TYP";
case (TTL_INDEX):
return "TTL";
case (NXH_INDEX):
return "NXH";
default:
return String.valueOf(b);
}
}
/**
* Returns a NetworkPacket given a byte array.
*
* @param d the d contained in the NetworkPacket
*/
public NetworkPacket(final byte[] d) {
data = new byte[MAX_PACKET_LENGTH];
setArray(d);
}
/**
* Creates an empty NetworkPacket. The TTL and LEN values are set to
* default.
*
* @param net Network ID of the packet
* @param src source address of the packet
* @param dst destination address of the packet
*/
| // Path: core/src/main/java/com/github/sdnwiselab/sdnwise/util/NodeAddress.java
// public final class NodeAddress implements Comparable<NodeAddress>, Serializable {
//
// /**
// * The default broadcast address.
// */
// public static final NodeAddress BROADCAST_ADDR = new NodeAddress("255.255");
//
// /**
// * The serialVersionUID as specified in the Serializable interface.
// */
// private static final long serialVersionUID = 1L;
//
// /**
// * A byte array containing the address. A NodeAddress is two bytes long.
// */
// private final byte[] addr = new byte[2];
//
// /**
// * Constructor method to create a Node Address from an int.
// *
// * @param a int value to set a Node Address.
// */
// public NodeAddress(final int a) {
// addr[0] = (byte) (a >>> Byte.SIZE);
// addr[1] = (byte) a;
// }
//
// /**
// *
// * Constructor method to create a Node Address from a byte array.
// *
// * @param a byte array value to set a Node Address.
// */
// public NodeAddress(final byte[] a) {
// if (a.length == 2) {
// addr[0] = a[0];
// addr[1] = a[1];
// }
// }
//
// /**
// * Constructor method to create a Node Address from a string.
// *
// * @param a string value to set a Node Address.
// */
// public NodeAddress(final String a) {
// String[] add = a.split("\\s*\\.\\s*");
// if (add.length == 2) {
// addr[0] = (byte) Integer.parseInt(add[0]);
// addr[1] = (byte) Integer.parseInt(add[1]);
// } else {
// int adr = Integer.parseInt(a);
// addr[0] = (byte) (adr >>> Byte.SIZE);
// addr[1] = (byte) adr;
// }
// }
//
// /**
// * Constructor method to create a Node Address from two int.
// *
// * @param addr0 int value to set fist part of Node Address.
// * @param addr1 int value to set second part of a Node Address.
// */
// public NodeAddress(final int addr0, final int addr1) {
// addr[0] = (byte) addr0;
// addr[1] = (byte) addr1;
// }
//
// @Override
// public int compareTo(final NodeAddress other) {
// return Integer.valueOf(intValue()).compareTo(other.intValue());
// }
//
// @Override
// public boolean equals(final Object obj) {
// return obj instanceof NodeAddress
// && ((NodeAddress) obj).intValue() == intValue();
// }
//
// /**
// * Gets the Node Address in Byte.
// *
// * @return a byte array of Node Address.
// */
// public byte[] getArray() {
// return new byte[]{addr[0], addr[1]};
// }
//
// /**
// * Gets the first Byte of a NodeAddress.
// *
// * @return a byte value of High Part of a NodeAddress.
// */
// public byte getHigh() {
// return addr[0];
// }
//
// /**
// * Gets the last Byte of a NodeAddress.
// *
// * @return a byte value of Low Part of a NodeAddress.
// */
// public byte getLow() {
// return addr[1];
// }
//
// @Override
// public int hashCode() {
// return Integer.valueOf(intValue()).hashCode();
// }
//
// /**
// * Returns the NodeAddress as an integer.
// *
// * @return int value of the NodeAddress.
// */
// public int intValue() {
// return mergeBytes(addr[0], addr[1]);
// }
//
// /**
// * Checks if the address is a broadcast address.
// *
// * @return true if equal to 255.255 false otherwise
// */
// public boolean isBroadcast() {
// return equals(BROADCAST_ADDR);
// }
//
// /**
// * Gets the Node Address in Byte.
// *
// * @return a byte array of Node Address.
// */
// public Byte[] toByteArray() {
// return new Byte[]{addr[0], addr[1]};
// }
//
// @Override
// public String toString() {
// return Byte.toUnsignedInt(addr[0]) + "." + Byte.toUnsignedInt(addr[1]);
// }
// }
// Path: core/src/main/java/com/github/sdnwiselab/sdnwise/packet/NetworkPacket.java
import com.github.sdnwiselab.sdnwise.util.NodeAddress;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.LinkedList;
return "SRC";
case (TYP_INDEX):
return "TYP";
case (TTL_INDEX):
return "TTL";
case (NXH_INDEX):
return "NXH";
default:
return String.valueOf(b);
}
}
/**
* Returns a NetworkPacket given a byte array.
*
* @param d the d contained in the NetworkPacket
*/
public NetworkPacket(final byte[] d) {
data = new byte[MAX_PACKET_LENGTH];
setArray(d);
}
/**
* Creates an empty NetworkPacket. The TTL and LEN values are set to
* default.
*
* @param net Network ID of the packet
* @param src source address of the packet
* @param dst destination address of the packet
*/
| public NetworkPacket(final int net, final NodeAddress src,
|
sdnwiselab/sdn-wise-java | ctrl/src/main/java/com/github/sdnwiselab/sdnwise/controlplane/ControlPlaneLayer.java | // Path: ctrl/src/main/java/com/github/sdnwiselab/sdnwise/adapter/AbstractAdapter.java
// public abstract class AbstractAdapter extends Observable implements Observer {
//
// /**
// * Logger.
// */
// protected static final Logger LOGGER = Logger.getLogger("ADP");
//
// private boolean active;
//
// /**
// * Creates an AbstractAdapter.
// */
// AbstractAdapter() {
// this.active = false;
// ControlPlaneLogger.setupLogger("ADP");
// }
//
// /**
// * Returns the state of the adapter.
// *
// * @return a boolean indicating if the adapter is open or not
// */
// public final boolean isActive() {
// return active;
// }
//
// /**
// * Returns the state of the adapter.
// *
// * @param act the state of the adapter
// * @return a boolean indicating if the adapter is active or not
// */
// protected final boolean setActive(final boolean act) {
// active = act;
// return active;
// }
//
// /**
// * Closes this adapter.
// *
// * @return a boolean indicating the correct ending of the operation
// */
// public abstract boolean close();
//
// /**
// * Opens this adapter.
// *
// * @return a boolean indicating the correct ending of the operation
// */
// public abstract boolean open();
//
// /**
// * Sends a byte array using this adapter.
// *
// * @param data the array to be sent
// */
// public abstract void send(byte[] data);
//
// @Override
// public final void update(final Observable o, final Object arg) {
// setChanged();
// notifyObservers(arg);
// }
//
// /**
// * Logs messages depending on the verbosity level.
// *
// * @param level a standard logging level
// * @param msg the string message to be logged
// */
// protected final void log(final Level level, final String msg) {
// LOGGER.log(level, msg);
// }
// }
| import com.github.sdnwiselab.sdnwise.adapter.AbstractAdapter;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Observer;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger; | /*
* Copyright (C) 2016 Seby
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.sdnwiselab.sdnwise.controlplane;
/**
* Models a layer of the Control Plane. Each layer has a lower and upper adapter
* and a scanner to intercept commands coming from the standard input
*
* @author Sebastiano Milardo
*/
public abstract class ControlPlaneLayer implements Observer, Runnable {
/**
* Charset in use.
*/
protected static final Charset UTF8_CHARSET = Charset.forName("UTF-8");
/**
* Manages the status of the layer.
*/
private boolean isStopped;
/**
* Identify the layer. This string is reported in each log message.
*/
private final String layerShortName;
/**
* Adapters.
*/ | // Path: ctrl/src/main/java/com/github/sdnwiselab/sdnwise/adapter/AbstractAdapter.java
// public abstract class AbstractAdapter extends Observable implements Observer {
//
// /**
// * Logger.
// */
// protected static final Logger LOGGER = Logger.getLogger("ADP");
//
// private boolean active;
//
// /**
// * Creates an AbstractAdapter.
// */
// AbstractAdapter() {
// this.active = false;
// ControlPlaneLogger.setupLogger("ADP");
// }
//
// /**
// * Returns the state of the adapter.
// *
// * @return a boolean indicating if the adapter is open or not
// */
// public final boolean isActive() {
// return active;
// }
//
// /**
// * Returns the state of the adapter.
// *
// * @param act the state of the adapter
// * @return a boolean indicating if the adapter is active or not
// */
// protected final boolean setActive(final boolean act) {
// active = act;
// return active;
// }
//
// /**
// * Closes this adapter.
// *
// * @return a boolean indicating the correct ending of the operation
// */
// public abstract boolean close();
//
// /**
// * Opens this adapter.
// *
// * @return a boolean indicating the correct ending of the operation
// */
// public abstract boolean open();
//
// /**
// * Sends a byte array using this adapter.
// *
// * @param data the array to be sent
// */
// public abstract void send(byte[] data);
//
// @Override
// public final void update(final Observable o, final Object arg) {
// setChanged();
// notifyObservers(arg);
// }
//
// /**
// * Logs messages depending on the verbosity level.
// *
// * @param level a standard logging level
// * @param msg the string message to be logged
// */
// protected final void log(final Level level, final String msg) {
// LOGGER.log(level, msg);
// }
// }
// Path: ctrl/src/main/java/com/github/sdnwiselab/sdnwise/controlplane/ControlPlaneLayer.java
import com.github.sdnwiselab.sdnwise.adapter.AbstractAdapter;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Observer;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
/*
* Copyright (C) 2016 Seby
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.sdnwiselab.sdnwise.controlplane;
/**
* Models a layer of the Control Plane. Each layer has a lower and upper adapter
* and a scanner to intercept commands coming from the standard input
*
* @author Sebastiano Milardo
*/
public abstract class ControlPlaneLayer implements Observer, Runnable {
/**
* Charset in use.
*/
protected static final Charset UTF8_CHARSET = Charset.forName("UTF-8");
/**
* Manages the status of the layer.
*/
private boolean isStopped;
/**
* Identify the layer. This string is reported in each log message.
*/
private final String layerShortName;
/**
* Adapters.
*/ | private final List<AbstractAdapter> lower, upper; |
sdnwiselab/sdn-wise-java | core/src/main/java/com/github/sdnwiselab/sdnwise/flowtable/ForwardUnicastAction.java | // Path: core/src/main/java/com/github/sdnwiselab/sdnwise/util/NodeAddress.java
// public final class NodeAddress implements Comparable<NodeAddress>, Serializable {
//
// /**
// * The default broadcast address.
// */
// public static final NodeAddress BROADCAST_ADDR = new NodeAddress("255.255");
//
// /**
// * The serialVersionUID as specified in the Serializable interface.
// */
// private static final long serialVersionUID = 1L;
//
// /**
// * A byte array containing the address. A NodeAddress is two bytes long.
// */
// private final byte[] addr = new byte[2];
//
// /**
// * Constructor method to create a Node Address from an int.
// *
// * @param a int value to set a Node Address.
// */
// public NodeAddress(final int a) {
// addr[0] = (byte) (a >>> Byte.SIZE);
// addr[1] = (byte) a;
// }
//
// /**
// *
// * Constructor method to create a Node Address from a byte array.
// *
// * @param a byte array value to set a Node Address.
// */
// public NodeAddress(final byte[] a) {
// if (a.length == 2) {
// addr[0] = a[0];
// addr[1] = a[1];
// }
// }
//
// /**
// * Constructor method to create a Node Address from a string.
// *
// * @param a string value to set a Node Address.
// */
// public NodeAddress(final String a) {
// String[] add = a.split("\\s*\\.\\s*");
// if (add.length == 2) {
// addr[0] = (byte) Integer.parseInt(add[0]);
// addr[1] = (byte) Integer.parseInt(add[1]);
// } else {
// int adr = Integer.parseInt(a);
// addr[0] = (byte) (adr >>> Byte.SIZE);
// addr[1] = (byte) adr;
// }
// }
//
// /**
// * Constructor method to create a Node Address from two int.
// *
// * @param addr0 int value to set fist part of Node Address.
// * @param addr1 int value to set second part of a Node Address.
// */
// public NodeAddress(final int addr0, final int addr1) {
// addr[0] = (byte) addr0;
// addr[1] = (byte) addr1;
// }
//
// @Override
// public int compareTo(final NodeAddress other) {
// return Integer.valueOf(intValue()).compareTo(other.intValue());
// }
//
// @Override
// public boolean equals(final Object obj) {
// return obj instanceof NodeAddress
// && ((NodeAddress) obj).intValue() == intValue();
// }
//
// /**
// * Gets the Node Address in Byte.
// *
// * @return a byte array of Node Address.
// */
// public byte[] getArray() {
// return new byte[]{addr[0], addr[1]};
// }
//
// /**
// * Gets the first Byte of a NodeAddress.
// *
// * @return a byte value of High Part of a NodeAddress.
// */
// public byte getHigh() {
// return addr[0];
// }
//
// /**
// * Gets the last Byte of a NodeAddress.
// *
// * @return a byte value of Low Part of a NodeAddress.
// */
// public byte getLow() {
// return addr[1];
// }
//
// @Override
// public int hashCode() {
// return Integer.valueOf(intValue()).hashCode();
// }
//
// /**
// * Returns the NodeAddress as an integer.
// *
// * @return int value of the NodeAddress.
// */
// public int intValue() {
// return mergeBytes(addr[0], addr[1]);
// }
//
// /**
// * Checks if the address is a broadcast address.
// *
// * @return true if equal to 255.255 false otherwise
// */
// public boolean isBroadcast() {
// return equals(BROADCAST_ADDR);
// }
//
// /**
// * Gets the Node Address in Byte.
// *
// * @return a byte array of Node Address.
// */
// public Byte[] toByteArray() {
// return new Byte[]{addr[0], addr[1]};
// }
//
// @Override
// public String toString() {
// return Byte.toUnsignedInt(addr[0]) + "." + Byte.toUnsignedInt(addr[1]);
// }
// }
| import static com.github.sdnwiselab.sdnwise.flowtable.AbstractAction.Action.FORWARD_U;
import com.github.sdnwiselab.sdnwise.util.NodeAddress; | /*
* Copyright (C) 2015 Seby
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.sdnwiselab.sdnwise.flowtable;
/**
* Representation of the ForwardUnicast action. A packet which is forwarded in
* unicast is received by the node specified.
*
* @author Sebastiano Milardo
*/
public final class ForwardUnicastAction extends AbstractForwardAction {
/**
* Creates a ForwardUnicast action. The next hop is set by using the String.
* An example of a string is "FORWARD_U 0.1" without quotes.
*
* @param str the string representing the ForwardUnicast action
*/
public ForwardUnicastAction(final String str) {
super(FORWARD_U);
if (FORWARD_U.name().equals(str.split(" ")[0].trim())) { | // Path: core/src/main/java/com/github/sdnwiselab/sdnwise/util/NodeAddress.java
// public final class NodeAddress implements Comparable<NodeAddress>, Serializable {
//
// /**
// * The default broadcast address.
// */
// public static final NodeAddress BROADCAST_ADDR = new NodeAddress("255.255");
//
// /**
// * The serialVersionUID as specified in the Serializable interface.
// */
// private static final long serialVersionUID = 1L;
//
// /**
// * A byte array containing the address. A NodeAddress is two bytes long.
// */
// private final byte[] addr = new byte[2];
//
// /**
// * Constructor method to create a Node Address from an int.
// *
// * @param a int value to set a Node Address.
// */
// public NodeAddress(final int a) {
// addr[0] = (byte) (a >>> Byte.SIZE);
// addr[1] = (byte) a;
// }
//
// /**
// *
// * Constructor method to create a Node Address from a byte array.
// *
// * @param a byte array value to set a Node Address.
// */
// public NodeAddress(final byte[] a) {
// if (a.length == 2) {
// addr[0] = a[0];
// addr[1] = a[1];
// }
// }
//
// /**
// * Constructor method to create a Node Address from a string.
// *
// * @param a string value to set a Node Address.
// */
// public NodeAddress(final String a) {
// String[] add = a.split("\\s*\\.\\s*");
// if (add.length == 2) {
// addr[0] = (byte) Integer.parseInt(add[0]);
// addr[1] = (byte) Integer.parseInt(add[1]);
// } else {
// int adr = Integer.parseInt(a);
// addr[0] = (byte) (adr >>> Byte.SIZE);
// addr[1] = (byte) adr;
// }
// }
//
// /**
// * Constructor method to create a Node Address from two int.
// *
// * @param addr0 int value to set fist part of Node Address.
// * @param addr1 int value to set second part of a Node Address.
// */
// public NodeAddress(final int addr0, final int addr1) {
// addr[0] = (byte) addr0;
// addr[1] = (byte) addr1;
// }
//
// @Override
// public int compareTo(final NodeAddress other) {
// return Integer.valueOf(intValue()).compareTo(other.intValue());
// }
//
// @Override
// public boolean equals(final Object obj) {
// return obj instanceof NodeAddress
// && ((NodeAddress) obj).intValue() == intValue();
// }
//
// /**
// * Gets the Node Address in Byte.
// *
// * @return a byte array of Node Address.
// */
// public byte[] getArray() {
// return new byte[]{addr[0], addr[1]};
// }
//
// /**
// * Gets the first Byte of a NodeAddress.
// *
// * @return a byte value of High Part of a NodeAddress.
// */
// public byte getHigh() {
// return addr[0];
// }
//
// /**
// * Gets the last Byte of a NodeAddress.
// *
// * @return a byte value of Low Part of a NodeAddress.
// */
// public byte getLow() {
// return addr[1];
// }
//
// @Override
// public int hashCode() {
// return Integer.valueOf(intValue()).hashCode();
// }
//
// /**
// * Returns the NodeAddress as an integer.
// *
// * @return int value of the NodeAddress.
// */
// public int intValue() {
// return mergeBytes(addr[0], addr[1]);
// }
//
// /**
// * Checks if the address is a broadcast address.
// *
// * @return true if equal to 255.255 false otherwise
// */
// public boolean isBroadcast() {
// return equals(BROADCAST_ADDR);
// }
//
// /**
// * Gets the Node Address in Byte.
// *
// * @return a byte array of Node Address.
// */
// public Byte[] toByteArray() {
// return new Byte[]{addr[0], addr[1]};
// }
//
// @Override
// public String toString() {
// return Byte.toUnsignedInt(addr[0]) + "." + Byte.toUnsignedInt(addr[1]);
// }
// }
// Path: core/src/main/java/com/github/sdnwiselab/sdnwise/flowtable/ForwardUnicastAction.java
import static com.github.sdnwiselab.sdnwise.flowtable.AbstractAction.Action.FORWARD_U;
import com.github.sdnwiselab.sdnwise.util.NodeAddress;
/*
* Copyright (C) 2015 Seby
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.sdnwiselab.sdnwise.flowtable;
/**
* Representation of the ForwardUnicast action. A packet which is forwarded in
* unicast is received by the node specified.
*
* @author Sebastiano Milardo
*/
public final class ForwardUnicastAction extends AbstractForwardAction {
/**
* Creates a ForwardUnicast action. The next hop is set by using the String.
* An example of a string is "FORWARD_U 0.1" without quotes.
*
* @param str the string representing the ForwardUnicast action
*/
public ForwardUnicastAction(final String str) {
super(FORWARD_U);
if (FORWARD_U.name().equals(str.split(" ")[0].trim())) { | setNextHop(new NodeAddress(str.split(" ")[1].trim())); |
sdnwiselab/sdn-wise-java | core/src/main/java/com/github/sdnwiselab/sdnwise/packet/RequestPacket.java | // Path: core/src/main/java/com/github/sdnwiselab/sdnwise/util/NodeAddress.java
// public final class NodeAddress implements Comparable<NodeAddress>, Serializable {
//
// /**
// * The default broadcast address.
// */
// public static final NodeAddress BROADCAST_ADDR = new NodeAddress("255.255");
//
// /**
// * The serialVersionUID as specified in the Serializable interface.
// */
// private static final long serialVersionUID = 1L;
//
// /**
// * A byte array containing the address. A NodeAddress is two bytes long.
// */
// private final byte[] addr = new byte[2];
//
// /**
// * Constructor method to create a Node Address from an int.
// *
// * @param a int value to set a Node Address.
// */
// public NodeAddress(final int a) {
// addr[0] = (byte) (a >>> Byte.SIZE);
// addr[1] = (byte) a;
// }
//
// /**
// *
// * Constructor method to create a Node Address from a byte array.
// *
// * @param a byte array value to set a Node Address.
// */
// public NodeAddress(final byte[] a) {
// if (a.length == 2) {
// addr[0] = a[0];
// addr[1] = a[1];
// }
// }
//
// /**
// * Constructor method to create a Node Address from a string.
// *
// * @param a string value to set a Node Address.
// */
// public NodeAddress(final String a) {
// String[] add = a.split("\\s*\\.\\s*");
// if (add.length == 2) {
// addr[0] = (byte) Integer.parseInt(add[0]);
// addr[1] = (byte) Integer.parseInt(add[1]);
// } else {
// int adr = Integer.parseInt(a);
// addr[0] = (byte) (adr >>> Byte.SIZE);
// addr[1] = (byte) adr;
// }
// }
//
// /**
// * Constructor method to create a Node Address from two int.
// *
// * @param addr0 int value to set fist part of Node Address.
// * @param addr1 int value to set second part of a Node Address.
// */
// public NodeAddress(final int addr0, final int addr1) {
// addr[0] = (byte) addr0;
// addr[1] = (byte) addr1;
// }
//
// @Override
// public int compareTo(final NodeAddress other) {
// return Integer.valueOf(intValue()).compareTo(other.intValue());
// }
//
// @Override
// public boolean equals(final Object obj) {
// return obj instanceof NodeAddress
// && ((NodeAddress) obj).intValue() == intValue();
// }
//
// /**
// * Gets the Node Address in Byte.
// *
// * @return a byte array of Node Address.
// */
// public byte[] getArray() {
// return new byte[]{addr[0], addr[1]};
// }
//
// /**
// * Gets the first Byte of a NodeAddress.
// *
// * @return a byte value of High Part of a NodeAddress.
// */
// public byte getHigh() {
// return addr[0];
// }
//
// /**
// * Gets the last Byte of a NodeAddress.
// *
// * @return a byte value of Low Part of a NodeAddress.
// */
// public byte getLow() {
// return addr[1];
// }
//
// @Override
// public int hashCode() {
// return Integer.valueOf(intValue()).hashCode();
// }
//
// /**
// * Returns the NodeAddress as an integer.
// *
// * @return int value of the NodeAddress.
// */
// public int intValue() {
// return mergeBytes(addr[0], addr[1]);
// }
//
// /**
// * Checks if the address is a broadcast address.
// *
// * @return true if equal to 255.255 false otherwise
// */
// public boolean isBroadcast() {
// return equals(BROADCAST_ADDR);
// }
//
// /**
// * Gets the Node Address in Byte.
// *
// * @return a byte array of Node Address.
// */
// public Byte[] toByteArray() {
// return new Byte[]{addr[0], addr[1]};
// }
//
// @Override
// public String toString() {
// return Byte.toUnsignedInt(addr[0]) + "." + Byte.toUnsignedInt(addr[1]);
// }
// }
//
// Path: core/src/main/java/com/github/sdnwiselab/sdnwise/util/Utils.java
// public static byte[] concatByteArray(final byte[] a, final byte[] b) {
// return ByteBuffer.allocate(a.length + b.length).put(a).put(b).array();
// }
| import static com.github.sdnwiselab.sdnwise.packet.NetworkPacket.REQUEST;
import com.github.sdnwiselab.sdnwise.util.NodeAddress;
import static com.github.sdnwiselab.sdnwise.util.Utils.concatByteArray; | payload = new byte[remaining];
} else {
payload = new byte[REQUEST_PAYLOAD_SIZE];
}
System.arraycopy(buf, 0, payload, 0, payload.length);
RequestPacket np = new RequestPacket(net, src, dst, id, 0, i, payload);
ll[0] = np;
if (i > 1) {
payload = new byte[remaining];
System.arraycopy(buf, REQUEST_PAYLOAD_SIZE, payload, 0, remaining);
np = new RequestPacket(net, src, dst, id, 1, i, payload);
ll[1] = np;
}
return ll;
}
/**
* Merges two Request packet to obtain the original packet.
*
* @param rp0 the first request packet
* @param rp1 the second request packet
* @return the NetworkPacket contained in the two Request packets
*/
public static NetworkPacket mergePackets(final RequestPacket rp0,
final RequestPacket rp1) {
if (rp0.getPart() == 0) {
return new NetworkPacket( | // Path: core/src/main/java/com/github/sdnwiselab/sdnwise/util/NodeAddress.java
// public final class NodeAddress implements Comparable<NodeAddress>, Serializable {
//
// /**
// * The default broadcast address.
// */
// public static final NodeAddress BROADCAST_ADDR = new NodeAddress("255.255");
//
// /**
// * The serialVersionUID as specified in the Serializable interface.
// */
// private static final long serialVersionUID = 1L;
//
// /**
// * A byte array containing the address. A NodeAddress is two bytes long.
// */
// private final byte[] addr = new byte[2];
//
// /**
// * Constructor method to create a Node Address from an int.
// *
// * @param a int value to set a Node Address.
// */
// public NodeAddress(final int a) {
// addr[0] = (byte) (a >>> Byte.SIZE);
// addr[1] = (byte) a;
// }
//
// /**
// *
// * Constructor method to create a Node Address from a byte array.
// *
// * @param a byte array value to set a Node Address.
// */
// public NodeAddress(final byte[] a) {
// if (a.length == 2) {
// addr[0] = a[0];
// addr[1] = a[1];
// }
// }
//
// /**
// * Constructor method to create a Node Address from a string.
// *
// * @param a string value to set a Node Address.
// */
// public NodeAddress(final String a) {
// String[] add = a.split("\\s*\\.\\s*");
// if (add.length == 2) {
// addr[0] = (byte) Integer.parseInt(add[0]);
// addr[1] = (byte) Integer.parseInt(add[1]);
// } else {
// int adr = Integer.parseInt(a);
// addr[0] = (byte) (adr >>> Byte.SIZE);
// addr[1] = (byte) adr;
// }
// }
//
// /**
// * Constructor method to create a Node Address from two int.
// *
// * @param addr0 int value to set fist part of Node Address.
// * @param addr1 int value to set second part of a Node Address.
// */
// public NodeAddress(final int addr0, final int addr1) {
// addr[0] = (byte) addr0;
// addr[1] = (byte) addr1;
// }
//
// @Override
// public int compareTo(final NodeAddress other) {
// return Integer.valueOf(intValue()).compareTo(other.intValue());
// }
//
// @Override
// public boolean equals(final Object obj) {
// return obj instanceof NodeAddress
// && ((NodeAddress) obj).intValue() == intValue();
// }
//
// /**
// * Gets the Node Address in Byte.
// *
// * @return a byte array of Node Address.
// */
// public byte[] getArray() {
// return new byte[]{addr[0], addr[1]};
// }
//
// /**
// * Gets the first Byte of a NodeAddress.
// *
// * @return a byte value of High Part of a NodeAddress.
// */
// public byte getHigh() {
// return addr[0];
// }
//
// /**
// * Gets the last Byte of a NodeAddress.
// *
// * @return a byte value of Low Part of a NodeAddress.
// */
// public byte getLow() {
// return addr[1];
// }
//
// @Override
// public int hashCode() {
// return Integer.valueOf(intValue()).hashCode();
// }
//
// /**
// * Returns the NodeAddress as an integer.
// *
// * @return int value of the NodeAddress.
// */
// public int intValue() {
// return mergeBytes(addr[0], addr[1]);
// }
//
// /**
// * Checks if the address is a broadcast address.
// *
// * @return true if equal to 255.255 false otherwise
// */
// public boolean isBroadcast() {
// return equals(BROADCAST_ADDR);
// }
//
// /**
// * Gets the Node Address in Byte.
// *
// * @return a byte array of Node Address.
// */
// public Byte[] toByteArray() {
// return new Byte[]{addr[0], addr[1]};
// }
//
// @Override
// public String toString() {
// return Byte.toUnsignedInt(addr[0]) + "." + Byte.toUnsignedInt(addr[1]);
// }
// }
//
// Path: core/src/main/java/com/github/sdnwiselab/sdnwise/util/Utils.java
// public static byte[] concatByteArray(final byte[] a, final byte[] b) {
// return ByteBuffer.allocate(a.length + b.length).put(a).put(b).array();
// }
// Path: core/src/main/java/com/github/sdnwiselab/sdnwise/packet/RequestPacket.java
import static com.github.sdnwiselab.sdnwise.packet.NetworkPacket.REQUEST;
import com.github.sdnwiselab.sdnwise.util.NodeAddress;
import static com.github.sdnwiselab.sdnwise.util.Utils.concatByteArray;
payload = new byte[remaining];
} else {
payload = new byte[REQUEST_PAYLOAD_SIZE];
}
System.arraycopy(buf, 0, payload, 0, payload.length);
RequestPacket np = new RequestPacket(net, src, dst, id, 0, i, payload);
ll[0] = np;
if (i > 1) {
payload = new byte[remaining];
System.arraycopy(buf, REQUEST_PAYLOAD_SIZE, payload, 0, remaining);
np = new RequestPacket(net, src, dst, id, 1, i, payload);
ll[1] = np;
}
return ll;
}
/**
* Merges two Request packet to obtain the original packet.
*
* @param rp0 the first request packet
* @param rp1 the second request packet
* @return the NetworkPacket contained in the two Request packets
*/
public static NetworkPacket mergePackets(final RequestPacket rp0,
final RequestPacket rp1) {
if (rp0.getPart() == 0) {
return new NetworkPacket( | concatByteArray(rp0.getData(), rp1.getData())); |
sdnwiselab/sdn-wise-java | core/src/main/java/com/github/sdnwiselab/sdnwise/flowtable/ActionBuilder.java | // Path: core/src/main/java/com/github/sdnwiselab/sdnwise/flowtable/AbstractAction.java
// public enum Action {
// /**
// * An empty action.
// */
// NULL(0),
// /**
// * Forward to a destination in unicast.
// */
// FORWARD_U(1),
// /**
// * Forward to a destination in broadcast.
// */
// FORWARD_B(2),
// /**
// * Drops the packet.
// */
// DROP(3),
// /**
// * Creates a new Request packet containing the current packet and sends
// * it to the controller.
// */
// ASK(4),
// /**
// * Invokes a function.
// */
// FUNCTION(5),
// /**
// * Sets a byte in the status register or in the packet.
// */
// SET(6),
// /**
// * Matches the packet against the FlowTable.
// */
// MATCH(7);
//
// /**
// * A byte representing the action.
// */
// private final byte value;
//
// /**
// * Contains all the possible action values.
// */
// private static final Action[] A_VALUES = Action.values();
//
// /**
// * Returns the corresponting Action given a byte.
// *
// * @param value a byte representing the Action
// * @return the corresponding Action
// */
// public static Action fromByte(final byte value) {
// return A_VALUES[value];
// }
//
// /**
// * Creates a new Action.
// *
// * @param v a byte representing the action.
// */
// Action(final int v) {
// value = (byte) v;
// }
// }
//
// Path: core/src/main/java/com/github/sdnwiselab/sdnwise/flowtable/AbstractAction.java
// protected static final int TYPE_INDEX = 0;
| import com.github.sdnwiselab.sdnwise.flowtable.AbstractAction.Action;
import static com.github.sdnwiselab.sdnwise.flowtable.AbstractAction.TYPE_INDEX; | /*
* Copyright (C) 2015 SDN-WISE
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.sdnwiselab.sdnwise.flowtable;
/**
* @author Sebastiano Milardo
*/
public final class ActionBuilder {
/**
* Builds a class extending AbstractAction, given a String.
*
* @param val the String representing the action
* @return an object extending AbstractAction
*/
public static AbstractAction build(final String val) { | // Path: core/src/main/java/com/github/sdnwiselab/sdnwise/flowtable/AbstractAction.java
// public enum Action {
// /**
// * An empty action.
// */
// NULL(0),
// /**
// * Forward to a destination in unicast.
// */
// FORWARD_U(1),
// /**
// * Forward to a destination in broadcast.
// */
// FORWARD_B(2),
// /**
// * Drops the packet.
// */
// DROP(3),
// /**
// * Creates a new Request packet containing the current packet and sends
// * it to the controller.
// */
// ASK(4),
// /**
// * Invokes a function.
// */
// FUNCTION(5),
// /**
// * Sets a byte in the status register or in the packet.
// */
// SET(6),
// /**
// * Matches the packet against the FlowTable.
// */
// MATCH(7);
//
// /**
// * A byte representing the action.
// */
// private final byte value;
//
// /**
// * Contains all the possible action values.
// */
// private static final Action[] A_VALUES = Action.values();
//
// /**
// * Returns the corresponting Action given a byte.
// *
// * @param value a byte representing the Action
// * @return the corresponding Action
// */
// public static Action fromByte(final byte value) {
// return A_VALUES[value];
// }
//
// /**
// * Creates a new Action.
// *
// * @param v a byte representing the action.
// */
// Action(final int v) {
// value = (byte) v;
// }
// }
//
// Path: core/src/main/java/com/github/sdnwiselab/sdnwise/flowtable/AbstractAction.java
// protected static final int TYPE_INDEX = 0;
// Path: core/src/main/java/com/github/sdnwiselab/sdnwise/flowtable/ActionBuilder.java
import com.github.sdnwiselab.sdnwise.flowtable.AbstractAction.Action;
import static com.github.sdnwiselab.sdnwise.flowtable.AbstractAction.TYPE_INDEX;
/*
* Copyright (C) 2015 SDN-WISE
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.sdnwiselab.sdnwise.flowtable;
/**
* @author Sebastiano Milardo
*/
public final class ActionBuilder {
/**
* Builds a class extending AbstractAction, given a String.
*
* @param val the String representing the action
* @return an object extending AbstractAction
*/
public static AbstractAction build(final String val) { | switch (Action.valueOf(val.split(" ")[0])) { |
sdnwiselab/sdn-wise-java | core/src/main/java/com/github/sdnwiselab/sdnwise/flowtable/ActionBuilder.java | // Path: core/src/main/java/com/github/sdnwiselab/sdnwise/flowtable/AbstractAction.java
// public enum Action {
// /**
// * An empty action.
// */
// NULL(0),
// /**
// * Forward to a destination in unicast.
// */
// FORWARD_U(1),
// /**
// * Forward to a destination in broadcast.
// */
// FORWARD_B(2),
// /**
// * Drops the packet.
// */
// DROP(3),
// /**
// * Creates a new Request packet containing the current packet and sends
// * it to the controller.
// */
// ASK(4),
// /**
// * Invokes a function.
// */
// FUNCTION(5),
// /**
// * Sets a byte in the status register or in the packet.
// */
// SET(6),
// /**
// * Matches the packet against the FlowTable.
// */
// MATCH(7);
//
// /**
// * A byte representing the action.
// */
// private final byte value;
//
// /**
// * Contains all the possible action values.
// */
// private static final Action[] A_VALUES = Action.values();
//
// /**
// * Returns the corresponting Action given a byte.
// *
// * @param value a byte representing the Action
// * @return the corresponding Action
// */
// public static Action fromByte(final byte value) {
// return A_VALUES[value];
// }
//
// /**
// * Creates a new Action.
// *
// * @param v a byte representing the action.
// */
// Action(final int v) {
// value = (byte) v;
// }
// }
//
// Path: core/src/main/java/com/github/sdnwiselab/sdnwise/flowtable/AbstractAction.java
// protected static final int TYPE_INDEX = 0;
| import com.github.sdnwiselab.sdnwise.flowtable.AbstractAction.Action;
import static com.github.sdnwiselab.sdnwise.flowtable.AbstractAction.TYPE_INDEX; | /*
* Copyright (C) 2015 SDN-WISE
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.sdnwiselab.sdnwise.flowtable;
/**
* @author Sebastiano Milardo
*/
public final class ActionBuilder {
/**
* Builds a class extending AbstractAction, given a String.
*
* @param val the String representing the action
* @return an object extending AbstractAction
*/
public static AbstractAction build(final String val) {
switch (Action.valueOf(val.split(" ")[0])) {
case FORWARD_U:
return new ForwardUnicastAction(val);
case FORWARD_B:
return new ForwardBroadcastAction();
case SET:
return new SetAction(val);
case MATCH:
return new MatchAction();
case ASK:
return new AskAction();
case FUNCTION:
return new FunctionAction(val);
case DROP:
return new DropAction();
default:
throw new IllegalArgumentException();
}
}
/**
* Builds a class extending AbstractAction, given a byte array.
*
* @param array the byte[] representing the action
* @return an object extending AbstractAction
*/
public static AbstractAction build(final byte[] array) { | // Path: core/src/main/java/com/github/sdnwiselab/sdnwise/flowtable/AbstractAction.java
// public enum Action {
// /**
// * An empty action.
// */
// NULL(0),
// /**
// * Forward to a destination in unicast.
// */
// FORWARD_U(1),
// /**
// * Forward to a destination in broadcast.
// */
// FORWARD_B(2),
// /**
// * Drops the packet.
// */
// DROP(3),
// /**
// * Creates a new Request packet containing the current packet and sends
// * it to the controller.
// */
// ASK(4),
// /**
// * Invokes a function.
// */
// FUNCTION(5),
// /**
// * Sets a byte in the status register or in the packet.
// */
// SET(6),
// /**
// * Matches the packet against the FlowTable.
// */
// MATCH(7);
//
// /**
// * A byte representing the action.
// */
// private final byte value;
//
// /**
// * Contains all the possible action values.
// */
// private static final Action[] A_VALUES = Action.values();
//
// /**
// * Returns the corresponting Action given a byte.
// *
// * @param value a byte representing the Action
// * @return the corresponding Action
// */
// public static Action fromByte(final byte value) {
// return A_VALUES[value];
// }
//
// /**
// * Creates a new Action.
// *
// * @param v a byte representing the action.
// */
// Action(final int v) {
// value = (byte) v;
// }
// }
//
// Path: core/src/main/java/com/github/sdnwiselab/sdnwise/flowtable/AbstractAction.java
// protected static final int TYPE_INDEX = 0;
// Path: core/src/main/java/com/github/sdnwiselab/sdnwise/flowtable/ActionBuilder.java
import com.github.sdnwiselab.sdnwise.flowtable.AbstractAction.Action;
import static com.github.sdnwiselab.sdnwise.flowtable.AbstractAction.TYPE_INDEX;
/*
* Copyright (C) 2015 SDN-WISE
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.sdnwiselab.sdnwise.flowtable;
/**
* @author Sebastiano Milardo
*/
public final class ActionBuilder {
/**
* Builds a class extending AbstractAction, given a String.
*
* @param val the String representing the action
* @return an object extending AbstractAction
*/
public static AbstractAction build(final String val) {
switch (Action.valueOf(val.split(" ")[0])) {
case FORWARD_U:
return new ForwardUnicastAction(val);
case FORWARD_B:
return new ForwardBroadcastAction();
case SET:
return new SetAction(val);
case MATCH:
return new MatchAction();
case ASK:
return new AskAction();
case FUNCTION:
return new FunctionAction(val);
case DROP:
return new DropAction();
default:
throw new IllegalArgumentException();
}
}
/**
* Builds a class extending AbstractAction, given a byte array.
*
* @param array the byte[] representing the action
* @return an object extending AbstractAction
*/
public static AbstractAction build(final byte[] array) { | switch (Action.fromByte(array[TYPE_INDEX])) { |
sdnwiselab/sdn-wise-java | core/src/main/java/com/github/sdnwiselab/sdnwise/util/NodeAddress.java | // Path: core/src/main/java/com/github/sdnwiselab/sdnwise/util/Utils.java
// public static int mergeBytes(final int high, final int low) {
// int h = Byte.toUnsignedInt((byte) high);
// int l = Byte.toUnsignedInt((byte) low);
// return (h << Byte.SIZE) | l;
// }
| import static com.github.sdnwiselab.sdnwise.util.Utils.mergeBytes;
import java.io.Serializable;
|
/**
* Gets the first Byte of a NodeAddress.
*
* @return a byte value of High Part of a NodeAddress.
*/
public byte getHigh() {
return addr[0];
}
/**
* Gets the last Byte of a NodeAddress.
*
* @return a byte value of Low Part of a NodeAddress.
*/
public byte getLow() {
return addr[1];
}
@Override
public int hashCode() {
return Integer.valueOf(intValue()).hashCode();
}
/**
* Returns the NodeAddress as an integer.
*
* @return int value of the NodeAddress.
*/
public int intValue() {
| // Path: core/src/main/java/com/github/sdnwiselab/sdnwise/util/Utils.java
// public static int mergeBytes(final int high, final int low) {
// int h = Byte.toUnsignedInt((byte) high);
// int l = Byte.toUnsignedInt((byte) low);
// return (h << Byte.SIZE) | l;
// }
// Path: core/src/main/java/com/github/sdnwiselab/sdnwise/util/NodeAddress.java
import static com.github.sdnwiselab.sdnwise.util.Utils.mergeBytes;
import java.io.Serializable;
/**
* Gets the first Byte of a NodeAddress.
*
* @return a byte value of High Part of a NodeAddress.
*/
public byte getHigh() {
return addr[0];
}
/**
* Gets the last Byte of a NodeAddress.
*
* @return a byte value of Low Part of a NodeAddress.
*/
public byte getLow() {
return addr[1];
}
@Override
public int hashCode() {
return Integer.valueOf(intValue()).hashCode();
}
/**
* Returns the NodeAddress as an integer.
*
* @return int value of the NodeAddress.
*/
public int intValue() {
| return mergeBytes(addr[0], addr[1]);
|
Sergix/JTerm | src/main/java/jterm/Server.java | // Path: src/main/java/jterm/io/output/TextColor.java
// public enum TextColor {
// INPUT, PATH, PROMPT, INFO, ERROR;
//
// String ansi;
// Color color;
//
// public static void initHeadless() {
// //TODO: Switch these back when ANSI is fixed in terminal
// INPUT.ansi = "";
// PATH.ansi = "";
// PROMPT.ansi = "";
// INFO.ansi = "";
// ERROR.ansi = "";
// // INPUT.ansi = "\\u001b[31m";
// // PATH.ansi = "\\u001b[31m";
// // PROMPT.ansi = "\\u001b[31m";
// // INFO.ansi = "\\u001b[31m";
// // ERROR.ansi = "\\u001b[31m";
// }
//
// public static void initGui() {
// INPUT.color = new Color(255, 255, 255);
// PATH.color = new Color(142, 114, 77);
// PROMPT.color = new Color(193, 122, 27);
// INFO.color = new Color(150, 150, 150);
// ERROR.color = new Color(140, 40, 40);
// }
//
// public Color getColor() {
// return color;
// }
// }
| import jterm.io.output.TextColor;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList; | /*
* JTerm - a cross-platform terminal
* Copyright (C) 2017 Sergix, NCSGeek
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package jterm;
public class Server implements Runnable {
private Socket socket;
public static boolean run = true;
public static int port = 0;
private static String line;
public Server(Socket newSocket) {
socket = newSocket;
}
public void run() {
while (run) {
try {
InputStream input = socket.getInputStream();
BufferedReader bufferedSocketInput = new BufferedReader(new InputStreamReader(input));
line = bufferedSocketInput.readLine();
if (line.isEmpty()) {
break;
}
| // Path: src/main/java/jterm/io/output/TextColor.java
// public enum TextColor {
// INPUT, PATH, PROMPT, INFO, ERROR;
//
// String ansi;
// Color color;
//
// public static void initHeadless() {
// //TODO: Switch these back when ANSI is fixed in terminal
// INPUT.ansi = "";
// PATH.ansi = "";
// PROMPT.ansi = "";
// INFO.ansi = "";
// ERROR.ansi = "";
// // INPUT.ansi = "\\u001b[31m";
// // PATH.ansi = "\\u001b[31m";
// // PROMPT.ansi = "\\u001b[31m";
// // INFO.ansi = "\\u001b[31m";
// // ERROR.ansi = "\\u001b[31m";
// }
//
// public static void initGui() {
// INPUT.color = new Color(255, 255, 255);
// PATH.color = new Color(142, 114, 77);
// PROMPT.color = new Color(193, 122, 27);
// INFO.color = new Color(150, 150, 150);
// ERROR.color = new Color(140, 40, 40);
// }
//
// public Color getColor() {
// return color;
// }
// }
// Path: src/main/java/jterm/Server.java
import jterm.io.output.TextColor;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
/*
* JTerm - a cross-platform terminal
* Copyright (C) 2017 Sergix, NCSGeek
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package jterm;
public class Server implements Runnable {
private Socket socket;
public static boolean run = true;
public static int port = 0;
private static String line;
public Server(Socket newSocket) {
socket = newSocket;
}
public void run() {
while (run) {
try {
InputStream input = socket.getInputStream();
BufferedReader bufferedSocketInput = new BufferedReader(new InputStreamReader(input));
line = bufferedSocketInput.readLine();
if (line.isEmpty()) {
break;
}
| JTerm.out.println(TextColor.INFO, "\n" + line); |
Sergix/JTerm | src/main/java/jterm/Client.java | // Path: src/main/java/jterm/io/output/TextColor.java
// public enum TextColor {
// INPUT, PATH, PROMPT, INFO, ERROR;
//
// String ansi;
// Color color;
//
// public static void initHeadless() {
// //TODO: Switch these back when ANSI is fixed in terminal
// INPUT.ansi = "";
// PATH.ansi = "";
// PROMPT.ansi = "";
// INFO.ansi = "";
// ERROR.ansi = "";
// // INPUT.ansi = "\\u001b[31m";
// // PATH.ansi = "\\u001b[31m";
// // PROMPT.ansi = "\\u001b[31m";
// // INFO.ansi = "\\u001b[31m";
// // ERROR.ansi = "\\u001b[31m";
// }
//
// public static void initGui() {
// INPUT.color = new Color(255, 255, 255);
// PATH.color = new Color(142, 114, 77);
// PROMPT.color = new Color(193, 122, 27);
// INFO.color = new Color(150, 150, 150);
// ERROR.color = new Color(140, 40, 40);
// }
//
// public Color getColor() {
// return color;
// }
// }
| import java.util.ArrayList;
import jterm.io.output.TextColor;
import java.io.*;
import java.net.Socket; | /*
* JTerm - a cross-platform terminal
* Copyright (C) 2017 Sergix, NCSGeek
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package jterm;
public class Client implements Runnable {
private static BufferedReader input;
public void run() {
while (true) {
try {
String output = Client.input.readLine();
if (output != null) { | // Path: src/main/java/jterm/io/output/TextColor.java
// public enum TextColor {
// INPUT, PATH, PROMPT, INFO, ERROR;
//
// String ansi;
// Color color;
//
// public static void initHeadless() {
// //TODO: Switch these back when ANSI is fixed in terminal
// INPUT.ansi = "";
// PATH.ansi = "";
// PROMPT.ansi = "";
// INFO.ansi = "";
// ERROR.ansi = "";
// // INPUT.ansi = "\\u001b[31m";
// // PATH.ansi = "\\u001b[31m";
// // PROMPT.ansi = "\\u001b[31m";
// // INFO.ansi = "\\u001b[31m";
// // ERROR.ansi = "\\u001b[31m";
// }
//
// public static void initGui() {
// INPUT.color = new Color(255, 255, 255);
// PATH.color = new Color(142, 114, 77);
// PROMPT.color = new Color(193, 122, 27);
// INFO.color = new Color(150, 150, 150);
// ERROR.color = new Color(140, 40, 40);
// }
//
// public Color getColor() {
// return color;
// }
// }
// Path: src/main/java/jterm/Client.java
import java.util.ArrayList;
import jterm.io.output.TextColor;
import java.io.*;
import java.net.Socket;
/*
* JTerm - a cross-platform terminal
* Copyright (C) 2017 Sergix, NCSGeek
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package jterm;
public class Client implements Runnable {
private static BufferedReader input;
public void run() {
while (true) {
try {
String output = Client.input.readLine();
if (output != null) { | JTerm.out.println(TextColor.INFO, output); |
free46000/MultiItem | library/src/main/java/com/freelib/multiitem/item/HiddenItemInput.java | // Path: library/src/main/java/com/freelib/multiitem/adapter/holder/BaseViewHolder.java
// public class BaseViewHolder extends RecyclerView.ViewHolder {
// public ViewHolderManager viewHolderManager;
// public Object itemData;
//
//
// public BaseViewHolder(View itemView) {
// super(itemView);
// }
//
//
// public Object getItemData() {
// return itemData;
// }
//
// /**
// * header和footer的个数也计算在内
// * {@link #getAdapterPosition()}
// */
// public int getItemPosition() {
// return getAdapterPosition();
// }
//
// public ViewHolderManager getViewHolderManager() {
// return viewHolderManager;
// }
//
// }
| import com.freelib.multiitem.adapter.holder.BaseViewHolder; | package com.freelib.multiitem.item;
/**
* 隐藏域的录入Item
* Created by free46000 on 2017/4/13.
*/
public class HiddenItemInput extends BaseItemInput {
protected Object value;
/**
* @param key item对应key
* @param value item对应value
*/
public HiddenItemInput(String key, Object value) {
super(key);
this.value = value;
}
@Override | // Path: library/src/main/java/com/freelib/multiitem/adapter/holder/BaseViewHolder.java
// public class BaseViewHolder extends RecyclerView.ViewHolder {
// public ViewHolderManager viewHolderManager;
// public Object itemData;
//
//
// public BaseViewHolder(View itemView) {
// super(itemView);
// }
//
//
// public Object getItemData() {
// return itemData;
// }
//
// /**
// * header和footer的个数也计算在内
// * {@link #getAdapterPosition()}
// */
// public int getItemPosition() {
// return getAdapterPosition();
// }
//
// public ViewHolderManager getViewHolderManager() {
// return viewHolderManager;
// }
//
// }
// Path: library/src/main/java/com/freelib/multiitem/item/HiddenItemInput.java
import com.freelib.multiitem.adapter.holder.BaseViewHolder;
package com.freelib.multiitem.item;
/**
* 隐藏域的录入Item
* Created by free46000 on 2017/4/13.
*/
public class HiddenItemInput extends BaseItemInput {
protected Object value;
/**
* @param key item对应key
* @param value item对应value
*/
public HiddenItemInput(String key, Object value) {
super(key);
this.value = value;
}
@Override | public void onBindViewHolder(BaseViewHolder holder, Object o) { |
free46000/MultiItem | library/src/main/java/com/freelib/multiitem/adapter/holder/ViewHolderManager.java | // Path: library/src/main/java/com/freelib/multiitem/item/ItemData.java
// public interface ItemData {
//
// /**
// * {@link View#setVisibility(int)}
// *
// * @param visibility @Visibility
// */
// void setVisibility(int visibility);
//
// /**
// * {@link View#getVisibility()}
// *
// * @return @Visibility
// */
// int getVisibility();
// }
| import android.databinding.DataBindingUtil;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView.ViewHolder;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.freelib.multiitem.item.ItemData; | package com.freelib.multiitem.adapter.holder;
/**
* ViewHolder的管理类
* 需要继承此类,实现ViewHolder的创建{@link #onCreateViewHolder}与绑定{@link #onBindViewHolder}
*
* @author free46000
*/
public abstract class ViewHolderManager<T, V extends BaseViewHolder> {
private boolean fullSpan;
private int spanSize;
protected ViewModel viewModel = new BaseViewModel();
/**
* 创建ViewHolder
* {@link android.support.v7.widget.RecyclerView.Adapter#onCreateViewHolder}
*/
@NonNull
public abstract V onCreateViewHolder(@NonNull ViewGroup parent);
/**
* 为ViewHolder绑定数据
* {@link android.support.v7.widget.RecyclerView.Adapter#onBindViewHolder}
*
* @param t 数据源
*/
public abstract void onBindViewHolder(V holder, T t);
/**
* 为ViewHolder绑定数据,并根据params做出相应设置
*
* @param t 数据源
* @param params {@link ViewHolderParams}
*/
public void onBindViewHolder(@NonNull V holder, @NonNull T t, @NonNull ViewHolderParams params) {
// TODO 如果以后有需要不直接在item view上设置Click事件,在MultiViewHolder增加itemHandlerView属性即可
if (isClickable()) {
holder.itemView.setOnClickListener(params.getClickListener());
holder.itemView.setOnLongClickListener(params.getLongClickListener());
}
//如果数据源是ItemData,则执行定制化处理 | // Path: library/src/main/java/com/freelib/multiitem/item/ItemData.java
// public interface ItemData {
//
// /**
// * {@link View#setVisibility(int)}
// *
// * @param visibility @Visibility
// */
// void setVisibility(int visibility);
//
// /**
// * {@link View#getVisibility()}
// *
// * @return @Visibility
// */
// int getVisibility();
// }
// Path: library/src/main/java/com/freelib/multiitem/adapter/holder/ViewHolderManager.java
import android.databinding.DataBindingUtil;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView.ViewHolder;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.freelib.multiitem.item.ItemData;
package com.freelib.multiitem.adapter.holder;
/**
* ViewHolder的管理类
* 需要继承此类,实现ViewHolder的创建{@link #onCreateViewHolder}与绑定{@link #onBindViewHolder}
*
* @author free46000
*/
public abstract class ViewHolderManager<T, V extends BaseViewHolder> {
private boolean fullSpan;
private int spanSize;
protected ViewModel viewModel = new BaseViewModel();
/**
* 创建ViewHolder
* {@link android.support.v7.widget.RecyclerView.Adapter#onCreateViewHolder}
*/
@NonNull
public abstract V onCreateViewHolder(@NonNull ViewGroup parent);
/**
* 为ViewHolder绑定数据
* {@link android.support.v7.widget.RecyclerView.Adapter#onBindViewHolder}
*
* @param t 数据源
*/
public abstract void onBindViewHolder(V holder, T t);
/**
* 为ViewHolder绑定数据,并根据params做出相应设置
*
* @param t 数据源
* @param params {@link ViewHolderParams}
*/
public void onBindViewHolder(@NonNull V holder, @NonNull T t, @NonNull ViewHolderParams params) {
// TODO 如果以后有需要不直接在item view上设置Click事件,在MultiViewHolder增加itemHandlerView属性即可
if (isClickable()) {
holder.itemView.setOnClickListener(params.getClickListener());
holder.itemView.setOnLongClickListener(params.getLongClickListener());
}
//如果数据源是ItemData,则执行定制化处理 | if (t instanceof ItemData) { |
free46000/MultiItem | library/src/main/java/com/freelib/multiitem/animation/AnimationLoader.java | // Path: library/src/main/java/com/freelib/multiitem/adapter/holder/BaseViewHolder.java
// public class BaseViewHolder extends RecyclerView.ViewHolder {
// public ViewHolderManager viewHolderManager;
// public Object itemData;
//
//
// public BaseViewHolder(View itemView) {
// super(itemView);
// }
//
//
// public Object getItemData() {
// return itemData;
// }
//
// /**
// * header和footer的个数也计算在内
// * {@link #getAdapterPosition()}
// */
// public int getItemPosition() {
// return getAdapterPosition();
// }
//
// public ViewHolderManager getViewHolderManager() {
// return viewHolderManager;
// }
//
// }
| import android.animation.Animator;
import android.support.annotation.NonNull;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
import com.freelib.multiitem.adapter.holder.BaseViewHolder; | package com.freelib.multiitem.animation;
/**
* 动画Loader,处理动画逻辑
* Created by free46000 on 2017/5/22.
*/
public class AnimationLoader {
protected int lastAnimIndex = -1;
protected boolean isAnimEnable;
protected boolean isShowAnimWhenFirst;
protected BaseAnimation animation;
protected long animDuration = 400L;
protected Interpolator interpolator = new LinearInterpolator();
public void clear() {
lastAnimIndex = -1;
}
/**
* 打开加载动画
*
* @param animation BaseAnimation
* @param isShowAnimWhenFirstLoad 是否只有在第一次展示的时候才使用动画
*/
public void enableLoadAnimation(@NonNull BaseAnimation animation, boolean isShowAnimWhenFirstLoad) {
this.isAnimEnable = true;
this.isShowAnimWhenFirst = isShowAnimWhenFirstLoad;
this.animation = animation == null ? new SlideInLeftAnimation() : animation;
}
/**
* 根据条件开启动画
*
* @param holder BaseViewHolder
*/ | // Path: library/src/main/java/com/freelib/multiitem/adapter/holder/BaseViewHolder.java
// public class BaseViewHolder extends RecyclerView.ViewHolder {
// public ViewHolderManager viewHolderManager;
// public Object itemData;
//
//
// public BaseViewHolder(View itemView) {
// super(itemView);
// }
//
//
// public Object getItemData() {
// return itemData;
// }
//
// /**
// * header和footer的个数也计算在内
// * {@link #getAdapterPosition()}
// */
// public int getItemPosition() {
// return getAdapterPosition();
// }
//
// public ViewHolderManager getViewHolderManager() {
// return viewHolderManager;
// }
//
// }
// Path: library/src/main/java/com/freelib/multiitem/animation/AnimationLoader.java
import android.animation.Animator;
import android.support.annotation.NonNull;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
import com.freelib.multiitem.adapter.holder.BaseViewHolder;
package com.freelib.multiitem.animation;
/**
* 动画Loader,处理动画逻辑
* Created by free46000 on 2017/5/22.
*/
public class AnimationLoader {
protected int lastAnimIndex = -1;
protected boolean isAnimEnable;
protected boolean isShowAnimWhenFirst;
protected BaseAnimation animation;
protected long animDuration = 400L;
protected Interpolator interpolator = new LinearInterpolator();
public void clear() {
lastAnimIndex = -1;
}
/**
* 打开加载动画
*
* @param animation BaseAnimation
* @param isShowAnimWhenFirstLoad 是否只有在第一次展示的时候才使用动画
*/
public void enableLoadAnimation(@NonNull BaseAnimation animation, boolean isShowAnimWhenFirstLoad) {
this.isAnimEnable = true;
this.isShowAnimWhenFirst = isShowAnimWhenFirstLoad;
this.animation = animation == null ? new SlideInLeftAnimation() : animation;
}
/**
* 根据条件开启动画
*
* @param holder BaseViewHolder
*/ | public void startAnimation(@NonNull BaseViewHolder holder) { |
free46000/MultiItem | demo/src/main/java/com/freelib/multiitem/demo/viewholder/ImageAndTextManager.java | // Path: library/src/main/java/com/freelib/multiitem/adapter/holder/BaseViewHolder.java
// public class BaseViewHolder extends RecyclerView.ViewHolder {
// public ViewHolderManager viewHolderManager;
// public Object itemData;
//
//
// public BaseViewHolder(View itemView) {
// super(itemView);
// }
//
//
// public Object getItemData() {
// return itemData;
// }
//
// /**
// * header和footer的个数也计算在内
// * {@link #getAdapterPosition()}
// */
// public int getItemPosition() {
// return getAdapterPosition();
// }
//
// public ViewHolderManager getViewHolderManager() {
// return viewHolderManager;
// }
//
// }
//
// Path: library/src/main/java/com/freelib/multiitem/adapter/holder/BaseViewHolderManager.java
// public abstract class BaseViewHolderManager<T> extends ViewHolderManager<T, BaseViewHolder> {
// @Override
// public abstract void onBindViewHolder(BaseViewHolder holder, T t);
//
// @NonNull
// @Override
// public BaseViewHolder onCreateViewHolder(@NonNull ViewGroup parent) {
// BaseViewHolder viewHolder = new BaseViewHolder(getItemView(parent));
// onCreateViewHolder(viewHolder);
// return viewHolder;
// }
//
// /**
// * {@link #onCreateViewHolder}
// */
// protected void onCreateViewHolder(@NonNull BaseViewHolder holder) {
// }
//
// }
//
// Path: demo/src/main/java/com/freelib/multiitem/demo/bean/ImageTextBean.java
// public class ImageTextBean extends BaseItemData {
// private int img;
// private String imgUrl;
// private String text;
//
// public ImageTextBean(int img, String text) {
// this.img = img;
// this.text = text;
// }
//
// public ImageTextBean(String imgUrl, String text) {
// this.imgUrl = imgUrl;
// this.text = text;
// }
//
// public int getImg() {
// return img;
// }
//
// public void setImg(int img) {
// this.img = img;
// }
//
// public String getText() {
// return text;
// }
//
// public void setText(String text) {
// this.text = text;
// }
//
// public String getImgUrl() {
// return imgUrl;
// }
//
// public void setImgUrl(String imgUrl) {
// this.imgUrl = imgUrl;
// }
//
// @Override
// public String toString() {
// return text;
// }
// }
| import android.support.annotation.NonNull;
import android.widget.ImageView;
import android.widget.TextView;
import com.freelib.multiitem.adapter.holder.BaseViewHolder;
import com.freelib.multiitem.adapter.holder.BaseViewHolderManager;
import com.freelib.multiitem.demo.R;
import com.freelib.multiitem.demo.bean.ImageTextBean; | package com.freelib.multiitem.demo.viewholder;
/**
* @author free46000 2017/03/17
* @version v1.0
*/
public class ImageAndTextManager extends BaseViewHolderManager<ImageTextBean> {
@Override | // Path: library/src/main/java/com/freelib/multiitem/adapter/holder/BaseViewHolder.java
// public class BaseViewHolder extends RecyclerView.ViewHolder {
// public ViewHolderManager viewHolderManager;
// public Object itemData;
//
//
// public BaseViewHolder(View itemView) {
// super(itemView);
// }
//
//
// public Object getItemData() {
// return itemData;
// }
//
// /**
// * header和footer的个数也计算在内
// * {@link #getAdapterPosition()}
// */
// public int getItemPosition() {
// return getAdapterPosition();
// }
//
// public ViewHolderManager getViewHolderManager() {
// return viewHolderManager;
// }
//
// }
//
// Path: library/src/main/java/com/freelib/multiitem/adapter/holder/BaseViewHolderManager.java
// public abstract class BaseViewHolderManager<T> extends ViewHolderManager<T, BaseViewHolder> {
// @Override
// public abstract void onBindViewHolder(BaseViewHolder holder, T t);
//
// @NonNull
// @Override
// public BaseViewHolder onCreateViewHolder(@NonNull ViewGroup parent) {
// BaseViewHolder viewHolder = new BaseViewHolder(getItemView(parent));
// onCreateViewHolder(viewHolder);
// return viewHolder;
// }
//
// /**
// * {@link #onCreateViewHolder}
// */
// protected void onCreateViewHolder(@NonNull BaseViewHolder holder) {
// }
//
// }
//
// Path: demo/src/main/java/com/freelib/multiitem/demo/bean/ImageTextBean.java
// public class ImageTextBean extends BaseItemData {
// private int img;
// private String imgUrl;
// private String text;
//
// public ImageTextBean(int img, String text) {
// this.img = img;
// this.text = text;
// }
//
// public ImageTextBean(String imgUrl, String text) {
// this.imgUrl = imgUrl;
// this.text = text;
// }
//
// public int getImg() {
// return img;
// }
//
// public void setImg(int img) {
// this.img = img;
// }
//
// public String getText() {
// return text;
// }
//
// public void setText(String text) {
// this.text = text;
// }
//
// public String getImgUrl() {
// return imgUrl;
// }
//
// public void setImgUrl(String imgUrl) {
// this.imgUrl = imgUrl;
// }
//
// @Override
// public String toString() {
// return text;
// }
// }
// Path: demo/src/main/java/com/freelib/multiitem/demo/viewholder/ImageAndTextManager.java
import android.support.annotation.NonNull;
import android.widget.ImageView;
import android.widget.TextView;
import com.freelib.multiitem.adapter.holder.BaseViewHolder;
import com.freelib.multiitem.adapter.holder.BaseViewHolderManager;
import com.freelib.multiitem.demo.R;
import com.freelib.multiitem.demo.bean.ImageTextBean;
package com.freelib.multiitem.demo.viewholder;
/**
* @author free46000 2017/03/17
* @version v1.0
*/
public class ImageAndTextManager extends BaseViewHolderManager<ImageTextBean> {
@Override | public void onBindViewHolder(@NonNull BaseViewHolder holder, @NonNull ImageTextBean data) { |
free46000/MultiItem | demo/src/main/java/com/freelib/multiitem/demo/viewholder/SendMessageManager.java | // Path: library/src/main/java/com/freelib/multiitem/adapter/holder/BaseViewHolder.java
// public class BaseViewHolder extends RecyclerView.ViewHolder {
// public ViewHolderManager viewHolderManager;
// public Object itemData;
//
//
// public BaseViewHolder(View itemView) {
// super(itemView);
// }
//
//
// public Object getItemData() {
// return itemData;
// }
//
// /**
// * header和footer的个数也计算在内
// * {@link #getAdapterPosition()}
// */
// public int getItemPosition() {
// return getAdapterPosition();
// }
//
// public ViewHolderManager getViewHolderManager() {
// return viewHolderManager;
// }
//
// }
//
// Path: library/src/main/java/com/freelib/multiitem/adapter/holder/BaseViewHolderManager.java
// public abstract class BaseViewHolderManager<T> extends ViewHolderManager<T, BaseViewHolder> {
// @Override
// public abstract void onBindViewHolder(BaseViewHolder holder, T t);
//
// @NonNull
// @Override
// public BaseViewHolder onCreateViewHolder(@NonNull ViewGroup parent) {
// BaseViewHolder viewHolder = new BaseViewHolder(getItemView(parent));
// onCreateViewHolder(viewHolder);
// return viewHolder;
// }
//
// /**
// * {@link #onCreateViewHolder}
// */
// protected void onCreateViewHolder(@NonNull BaseViewHolder holder) {
// }
//
// }
//
// Path: demo/src/main/java/com/freelib/multiitem/demo/bean/MessageBean.java
// public class MessageBean {
// private String message;
// private String sender;
//
// public MessageBean(String message, String sender) {
// this.message = message;
// this.sender = sender;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// public String getSender() {
// return sender;
// }
//
// public void setSender(String sender) {
// this.sender = sender;
// }
// }
| import android.support.annotation.NonNull;
import android.widget.TextView;
import com.freelib.multiitem.adapter.holder.BaseViewHolder;
import com.freelib.multiitem.adapter.holder.BaseViewHolderManager;
import com.freelib.multiitem.demo.R;
import com.freelib.multiitem.demo.bean.MessageBean; | package com.freelib.multiitem.demo.viewholder;
/**
* @author free46000 2017/03/17
*/
public class SendMessageManager extends BaseViewHolderManager<MessageBean> {
@Override | // Path: library/src/main/java/com/freelib/multiitem/adapter/holder/BaseViewHolder.java
// public class BaseViewHolder extends RecyclerView.ViewHolder {
// public ViewHolderManager viewHolderManager;
// public Object itemData;
//
//
// public BaseViewHolder(View itemView) {
// super(itemView);
// }
//
//
// public Object getItemData() {
// return itemData;
// }
//
// /**
// * header和footer的个数也计算在内
// * {@link #getAdapterPosition()}
// */
// public int getItemPosition() {
// return getAdapterPosition();
// }
//
// public ViewHolderManager getViewHolderManager() {
// return viewHolderManager;
// }
//
// }
//
// Path: library/src/main/java/com/freelib/multiitem/adapter/holder/BaseViewHolderManager.java
// public abstract class BaseViewHolderManager<T> extends ViewHolderManager<T, BaseViewHolder> {
// @Override
// public abstract void onBindViewHolder(BaseViewHolder holder, T t);
//
// @NonNull
// @Override
// public BaseViewHolder onCreateViewHolder(@NonNull ViewGroup parent) {
// BaseViewHolder viewHolder = new BaseViewHolder(getItemView(parent));
// onCreateViewHolder(viewHolder);
// return viewHolder;
// }
//
// /**
// * {@link #onCreateViewHolder}
// */
// protected void onCreateViewHolder(@NonNull BaseViewHolder holder) {
// }
//
// }
//
// Path: demo/src/main/java/com/freelib/multiitem/demo/bean/MessageBean.java
// public class MessageBean {
// private String message;
// private String sender;
//
// public MessageBean(String message, String sender) {
// this.message = message;
// this.sender = sender;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// public String getSender() {
// return sender;
// }
//
// public void setSender(String sender) {
// this.sender = sender;
// }
// }
// Path: demo/src/main/java/com/freelib/multiitem/demo/viewholder/SendMessageManager.java
import android.support.annotation.NonNull;
import android.widget.TextView;
import com.freelib.multiitem.adapter.holder.BaseViewHolder;
import com.freelib.multiitem.adapter.holder.BaseViewHolderManager;
import com.freelib.multiitem.demo.R;
import com.freelib.multiitem.demo.bean.MessageBean;
package com.freelib.multiitem.demo.viewholder;
/**
* @author free46000 2017/03/17
*/
public class SendMessageManager extends BaseViewHolderManager<MessageBean> {
@Override | public void onBindViewHolder(@NonNull BaseViewHolder holder, @NonNull MessageBean data) { |
free46000/MultiItem | demo/src/main/java/com/freelib/multiitem/demo/input/ItemEdit.java | // Path: library/src/main/java/com/freelib/multiitem/adapter/holder/BaseViewHolder.java
// public class BaseViewHolder extends RecyclerView.ViewHolder {
// public ViewHolderManager viewHolderManager;
// public Object itemData;
//
//
// public BaseViewHolder(View itemView) {
// super(itemView);
// }
//
//
// public Object getItemData() {
// return itemData;
// }
//
// /**
// * header和footer的个数也计算在内
// * {@link #getAdapterPosition()}
// */
// public int getItemPosition() {
// return getAdapterPosition();
// }
//
// public ViewHolderManager getViewHolderManager() {
// return viewHolderManager;
// }
//
// }
//
// Path: library/src/main/java/com/freelib/multiitem/item/BaseItemInput.java
// public abstract class BaseItemInput<T extends BaseItemInput> extends InputHolderManager<T> implements ItemInput {
// protected String key;
//
// /**
// * @param key 录入对应key
// */
// public BaseItemInput(String key) {
// this.key = key;
// }
//
//
// @NonNull
// @Override
// public String getItemTypeName() {
// return toString();
// }
//
// @Override
// public InputHolderManager getViewHolderManager() {
// return this;
// }
//
// @Override
// public String getKey() {
// return key;
// }
//
// }
| import android.text.TextUtils;
import android.widget.EditText;
import android.widget.TextView;
import com.freelib.multiitem.adapter.holder.BaseViewHolder;
import com.freelib.multiitem.demo.R;
import com.freelib.multiitem.item.BaseItemInput; | package com.freelib.multiitem.demo.input;
/**
* ItemEdit
* Created by free46000 on 2017/4/12.
*/
public class ItemEdit extends BaseItemInput<ItemEdit> {
private EditText editText;
private String name;
private String defValue = "";
private String hint;
/**
* @param key 录入对应key
*/
public ItemEdit(String key) {
super(key);
}
/**
* 设置展示列名
*
* @param name 展示列名
*/
public ItemEdit setName(String name) {
this.name = name;
return this;
}
public ItemEdit setHint(String hint) {
this.hint = hint;
return this;
}
/**
* 设置默认值
*
* @param defValue 默认值
*/
public ItemEdit setDefValue(String defValue) {
this.defValue = defValue;
return this;
}
@Override
public String getValue() {
//返回录入的值,和{@link #getKey()}一起组装为Map 如果为null则不组装
return editText == null ? defValue : editText.getText().toString();
}
@Override
public boolean isValueValid() {
//是否验证有效,如Item不能为空,如用户手动更改,true:有效;false:无效
return !TextUtils.isEmpty(getValue());
}
@Override | // Path: library/src/main/java/com/freelib/multiitem/adapter/holder/BaseViewHolder.java
// public class BaseViewHolder extends RecyclerView.ViewHolder {
// public ViewHolderManager viewHolderManager;
// public Object itemData;
//
//
// public BaseViewHolder(View itemView) {
// super(itemView);
// }
//
//
// public Object getItemData() {
// return itemData;
// }
//
// /**
// * header和footer的个数也计算在内
// * {@link #getAdapterPosition()}
// */
// public int getItemPosition() {
// return getAdapterPosition();
// }
//
// public ViewHolderManager getViewHolderManager() {
// return viewHolderManager;
// }
//
// }
//
// Path: library/src/main/java/com/freelib/multiitem/item/BaseItemInput.java
// public abstract class BaseItemInput<T extends BaseItemInput> extends InputHolderManager<T> implements ItemInput {
// protected String key;
//
// /**
// * @param key 录入对应key
// */
// public BaseItemInput(String key) {
// this.key = key;
// }
//
//
// @NonNull
// @Override
// public String getItemTypeName() {
// return toString();
// }
//
// @Override
// public InputHolderManager getViewHolderManager() {
// return this;
// }
//
// @Override
// public String getKey() {
// return key;
// }
//
// }
// Path: demo/src/main/java/com/freelib/multiitem/demo/input/ItemEdit.java
import android.text.TextUtils;
import android.widget.EditText;
import android.widget.TextView;
import com.freelib.multiitem.adapter.holder.BaseViewHolder;
import com.freelib.multiitem.demo.R;
import com.freelib.multiitem.item.BaseItemInput;
package com.freelib.multiitem.demo.input;
/**
* ItemEdit
* Created by free46000 on 2017/4/12.
*/
public class ItemEdit extends BaseItemInput<ItemEdit> {
private EditText editText;
private String name;
private String defValue = "";
private String hint;
/**
* @param key 录入对应key
*/
public ItemEdit(String key) {
super(key);
}
/**
* 设置展示列名
*
* @param name 展示列名
*/
public ItemEdit setName(String name) {
this.name = name;
return this;
}
public ItemEdit setHint(String hint) {
this.hint = hint;
return this;
}
/**
* 设置默认值
*
* @param defValue 默认值
*/
public ItemEdit setDefValue(String defValue) {
this.defValue = defValue;
return this;
}
@Override
public String getValue() {
//返回录入的值,和{@link #getKey()}一起组装为Map 如果为null则不组装
return editText == null ? defValue : editText.getText().toString();
}
@Override
public boolean isValueValid() {
//是否验证有效,如Item不能为空,如用户手动更改,true:有效;false:无效
return !TextUtils.isEmpty(getValue());
}
@Override | protected void initInputView(BaseViewHolder holder) { |
free46000/MultiItem | library/src/main/java/com/freelib/multiitem/adapter/holder/ViewHolderParams.java | // Path: library/src/main/java/com/freelib/multiitem/listener/OnItemClickListener.java
// public abstract class OnItemClickListener implements View.OnClickListener {
//
// @Override
// public void onClick(View v) {
// BaseViewHolder viewHolder = ListenerUtil.getViewHolderByItemView(v);
// if (viewHolder == null) {
// return;
// }
//
// onItemClick(viewHolder);
// }
//
// /**
// * 点击回调 可以通过viewHolder get到需要的数据
// */
// public abstract void onItemClick(BaseViewHolder viewHolder);
//
//
// }
//
// Path: library/src/main/java/com/freelib/multiitem/listener/OnItemLongClickListener.java
// public abstract class OnItemLongClickListener implements View.OnLongClickListener {
//
// @Override
// public boolean onLongClick(View v) {
// BaseViewHolder viewHolder = ListenerUtil.getViewHolderByItemView(v);
// if (viewHolder == null) {
// return false;
// }
//
// onItemLongClick(viewHolder);
// return true;
// }
//
// /**
// * 点击回调 可以通过viewHolder get到需要的数据
// */
// protected abstract void onItemLongClick(BaseViewHolder viewHolder);
//
// }
| import com.freelib.multiitem.listener.OnItemClickListener;
import com.freelib.multiitem.listener.OnItemLongClickListener; | package com.freelib.multiitem.adapter.holder;
/**
* Created by free46000 on 2017/3/20.
*/
public class ViewHolderParams {
private OnItemClickListener clickListener; | // Path: library/src/main/java/com/freelib/multiitem/listener/OnItemClickListener.java
// public abstract class OnItemClickListener implements View.OnClickListener {
//
// @Override
// public void onClick(View v) {
// BaseViewHolder viewHolder = ListenerUtil.getViewHolderByItemView(v);
// if (viewHolder == null) {
// return;
// }
//
// onItemClick(viewHolder);
// }
//
// /**
// * 点击回调 可以通过viewHolder get到需要的数据
// */
// public abstract void onItemClick(BaseViewHolder viewHolder);
//
//
// }
//
// Path: library/src/main/java/com/freelib/multiitem/listener/OnItemLongClickListener.java
// public abstract class OnItemLongClickListener implements View.OnLongClickListener {
//
// @Override
// public boolean onLongClick(View v) {
// BaseViewHolder viewHolder = ListenerUtil.getViewHolderByItemView(v);
// if (viewHolder == null) {
// return false;
// }
//
// onItemLongClick(viewHolder);
// return true;
// }
//
// /**
// * 点击回调 可以通过viewHolder get到需要的数据
// */
// protected abstract void onItemLongClick(BaseViewHolder viewHolder);
//
// }
// Path: library/src/main/java/com/freelib/multiitem/adapter/holder/ViewHolderParams.java
import com.freelib.multiitem.listener.OnItemClickListener;
import com.freelib.multiitem.listener.OnItemLongClickListener;
package com.freelib.multiitem.adapter.holder;
/**
* Created by free46000 on 2017/3/20.
*/
public class ViewHolderParams {
private OnItemClickListener clickListener; | private OnItemLongClickListener longClickListener; |
free46000/MultiItem | library/src/main/java/com/freelib/multiitem/listener/ListenerUtil.java | // Path: library/src/main/java/com/freelib/multiitem/adapter/holder/BaseViewHolder.java
// public class BaseViewHolder extends RecyclerView.ViewHolder {
// public ViewHolderManager viewHolderManager;
// public Object itemData;
//
//
// public BaseViewHolder(View itemView) {
// super(itemView);
// }
//
//
// public Object getItemData() {
// return itemData;
// }
//
// /**
// * header和footer的个数也计算在内
// * {@link #getAdapterPosition()}
// */
// public int getItemPosition() {
// return getAdapterPosition();
// }
//
// public ViewHolderManager getViewHolderManager() {
// return viewHolderManager;
// }
//
// }
//
// Path: library/src/main/java/com/freelib/multiitem/common/Const.java
// public class Const {
// public static final int VIEW_HOLDER_TAG = -121;
// }
| import android.util.Log;
import android.view.View;
import com.freelib.multiitem.adapter.holder.BaseViewHolder;
import com.freelib.multiitem.common.Const; | package com.freelib.multiitem.listener;
/**
* @author free46000 2017/03/16
* @version v1.0
*/
public class ListenerUtil {
/**
* 通过点击的item view获取到BaseViewHolder
*
* @return BaseViewHolder
*/
public static BaseViewHolder getViewHolderByItemView(View view) { | // Path: library/src/main/java/com/freelib/multiitem/adapter/holder/BaseViewHolder.java
// public class BaseViewHolder extends RecyclerView.ViewHolder {
// public ViewHolderManager viewHolderManager;
// public Object itemData;
//
//
// public BaseViewHolder(View itemView) {
// super(itemView);
// }
//
//
// public Object getItemData() {
// return itemData;
// }
//
// /**
// * header和footer的个数也计算在内
// * {@link #getAdapterPosition()}
// */
// public int getItemPosition() {
// return getAdapterPosition();
// }
//
// public ViewHolderManager getViewHolderManager() {
// return viewHolderManager;
// }
//
// }
//
// Path: library/src/main/java/com/freelib/multiitem/common/Const.java
// public class Const {
// public static final int VIEW_HOLDER_TAG = -121;
// }
// Path: library/src/main/java/com/freelib/multiitem/listener/ListenerUtil.java
import android.util.Log;
import android.view.View;
import com.freelib.multiitem.adapter.holder.BaseViewHolder;
import com.freelib.multiitem.common.Const;
package com.freelib.multiitem.listener;
/**
* @author free46000 2017/03/16
* @version v1.0
*/
public class ListenerUtil {
/**
* 通过点击的item view获取到BaseViewHolder
*
* @return BaseViewHolder
*/
public static BaseViewHolder getViewHolderByItemView(View view) { | Object tag = view.getTag(Const.VIEW_HOLDER_TAG); |
free46000/MultiItem | demo/src/main/java/com/freelib/multiitem/demo/viewholder/ImageViewManager.java | // Path: library/src/main/java/com/freelib/multiitem/adapter/holder/BaseViewHolder.java
// public class BaseViewHolder extends RecyclerView.ViewHolder {
// public ViewHolderManager viewHolderManager;
// public Object itemData;
//
//
// public BaseViewHolder(View itemView) {
// super(itemView);
// }
//
//
// public Object getItemData() {
// return itemData;
// }
//
// /**
// * header和footer的个数也计算在内
// * {@link #getAdapterPosition()}
// */
// public int getItemPosition() {
// return getAdapterPosition();
// }
//
// public ViewHolderManager getViewHolderManager() {
// return viewHolderManager;
// }
//
// }
//
// Path: library/src/main/java/com/freelib/multiitem/adapter/holder/BaseViewHolderManager.java
// public abstract class BaseViewHolderManager<T> extends ViewHolderManager<T, BaseViewHolder> {
// @Override
// public abstract void onBindViewHolder(BaseViewHolder holder, T t);
//
// @NonNull
// @Override
// public BaseViewHolder onCreateViewHolder(@NonNull ViewGroup parent) {
// BaseViewHolder viewHolder = new BaseViewHolder(getItemView(parent));
// onCreateViewHolder(viewHolder);
// return viewHolder;
// }
//
// /**
// * {@link #onCreateViewHolder}
// */
// protected void onCreateViewHolder(@NonNull BaseViewHolder holder) {
// }
//
// }
//
// Path: demo/src/main/java/com/freelib/multiitem/demo/bean/ImageBean.java
// public class ImageBean {
// private int img;
//
// public ImageBean(int img) {
// this.img = img;
// }
//
// public int getImg() {
// return img;
// }
//
// public void setImg(int img) {
// this.img = img;
// }
//
// @Override
// public String toString() {
// return img + "";
// }
// }
| import android.support.annotation.NonNull;
import android.widget.ImageView;
import com.freelib.multiitem.adapter.holder.BaseViewHolder;
import com.freelib.multiitem.adapter.holder.BaseViewHolderManager;
import com.freelib.multiitem.demo.R;
import com.freelib.multiitem.demo.bean.ImageBean; | package com.freelib.multiitem.demo.viewholder;
/**
* @author free46000 2017/03/17
* @version v1.0
*/
public class ImageViewManager extends BaseViewHolderManager<ImageBean> {
@Override | // Path: library/src/main/java/com/freelib/multiitem/adapter/holder/BaseViewHolder.java
// public class BaseViewHolder extends RecyclerView.ViewHolder {
// public ViewHolderManager viewHolderManager;
// public Object itemData;
//
//
// public BaseViewHolder(View itemView) {
// super(itemView);
// }
//
//
// public Object getItemData() {
// return itemData;
// }
//
// /**
// * header和footer的个数也计算在内
// * {@link #getAdapterPosition()}
// */
// public int getItemPosition() {
// return getAdapterPosition();
// }
//
// public ViewHolderManager getViewHolderManager() {
// return viewHolderManager;
// }
//
// }
//
// Path: library/src/main/java/com/freelib/multiitem/adapter/holder/BaseViewHolderManager.java
// public abstract class BaseViewHolderManager<T> extends ViewHolderManager<T, BaseViewHolder> {
// @Override
// public abstract void onBindViewHolder(BaseViewHolder holder, T t);
//
// @NonNull
// @Override
// public BaseViewHolder onCreateViewHolder(@NonNull ViewGroup parent) {
// BaseViewHolder viewHolder = new BaseViewHolder(getItemView(parent));
// onCreateViewHolder(viewHolder);
// return viewHolder;
// }
//
// /**
// * {@link #onCreateViewHolder}
// */
// protected void onCreateViewHolder(@NonNull BaseViewHolder holder) {
// }
//
// }
//
// Path: demo/src/main/java/com/freelib/multiitem/demo/bean/ImageBean.java
// public class ImageBean {
// private int img;
//
// public ImageBean(int img) {
// this.img = img;
// }
//
// public int getImg() {
// return img;
// }
//
// public void setImg(int img) {
// this.img = img;
// }
//
// @Override
// public String toString() {
// return img + "";
// }
// }
// Path: demo/src/main/java/com/freelib/multiitem/demo/viewholder/ImageViewManager.java
import android.support.annotation.NonNull;
import android.widget.ImageView;
import com.freelib.multiitem.adapter.holder.BaseViewHolder;
import com.freelib.multiitem.adapter.holder.BaseViewHolderManager;
import com.freelib.multiitem.demo.R;
import com.freelib.multiitem.demo.bean.ImageBean;
package com.freelib.multiitem.demo.viewholder;
/**
* @author free46000 2017/03/17
* @version v1.0
*/
public class ImageViewManager extends BaseViewHolderManager<ImageBean> {
@Override | public void onBindViewHolder(@NonNull BaseViewHolder holder, @NonNull ImageBean data) { |
free46000/MultiItem | demo/src/main/java/com/freelib/multiitem/demo/viewholder/TextViewDragManager.java | // Path: library/src/main/java/com/freelib/multiitem/adapter/holder/BaseViewHolder.java
// public class BaseViewHolder extends RecyclerView.ViewHolder {
// public ViewHolderManager viewHolderManager;
// public Object itemData;
//
//
// public BaseViewHolder(View itemView) {
// super(itemView);
// }
//
//
// public Object getItemData() {
// return itemData;
// }
//
// /**
// * header和footer的个数也计算在内
// * {@link #getAdapterPosition()}
// */
// public int getItemPosition() {
// return getAdapterPosition();
// }
//
// public ViewHolderManager getViewHolderManager() {
// return viewHolderManager;
// }
//
// }
//
// Path: library/src/main/java/com/freelib/multiitem/adapter/holder/BaseViewHolderManager.java
// public abstract class BaseViewHolderManager<T> extends ViewHolderManager<T, BaseViewHolder> {
// @Override
// public abstract void onBindViewHolder(BaseViewHolder holder, T t);
//
// @NonNull
// @Override
// public BaseViewHolder onCreateViewHolder(@NonNull ViewGroup parent) {
// BaseViewHolder viewHolder = new BaseViewHolder(getItemView(parent));
// onCreateViewHolder(viewHolder);
// return viewHolder;
// }
//
// /**
// * {@link #onCreateViewHolder}
// */
// protected void onCreateViewHolder(@NonNull BaseViewHolder holder) {
// }
//
// }
//
// Path: demo/src/main/java/com/freelib/multiitem/demo/bean/TextDragBean.java
// public class TextDragBean extends BaseItemData implements ItemDrag {
// private String text;
// private boolean isCanMove = true;
// private boolean isCanChangeRecycler = true;
// private boolean isCanDrag = true;
//
// public TextDragBean(String text) {
// this.text = text;
// }
//
// public TextDragBean(String text, boolean isCanMove) {
// this.text = text;
// this.isCanMove = isCanMove;
// }
//
// public TextDragBean(String text, boolean isCanMove, boolean isCanChangeRecycler) {
// this.text = text;
// this.isCanMove = isCanMove;
// this.isCanChangeRecycler = isCanChangeRecycler;
// }
//
// public TextDragBean(String text, boolean isCanMove, boolean isCanChangeRecycler, boolean isCanDrag) {
// this.text = text;
// this.isCanMove = isCanMove;
// this.isCanChangeRecycler = isCanChangeRecycler;
// this.isCanDrag = isCanDrag;
// }
//
// public String getText() {
// return text;
// }
//
// public void setText(String text) {
// this.text = text;
// }
//
// @Override
// public String toString() {
// return text;
// }
//
// @Override
// public boolean isCanMove() {
// return isCanMove;
// }
//
// public void setCanMove(boolean canMove) {
// isCanMove = canMove;
// }
//
// @Override
// public boolean isCanChangeRecycler() {
// return isCanChangeRecycler;
// }
//
// public void setCanChangeRecycler(boolean canChangeRecycler) {
// isCanChangeRecycler = canChangeRecycler;
// }
//
// @Override
// public boolean isCanDrag() {
// return isCanDrag;
// }
//
// public void setCanDrag(boolean canDrag) {
// isCanDrag = canDrag;
// }
// }
| import android.support.annotation.NonNull;
import android.widget.TextView;
import com.freelib.multiitem.adapter.holder.BaseViewHolder;
import com.freelib.multiitem.adapter.holder.BaseViewHolderManager;
import com.freelib.multiitem.demo.R;
import com.freelib.multiitem.demo.bean.TextDragBean; | package com.freelib.multiitem.demo.viewholder;
/**
* @author free46000 2017/03/17
* @version v1.0
*/
public class TextViewDragManager extends BaseViewHolderManager<TextDragBean> {
@Override | // Path: library/src/main/java/com/freelib/multiitem/adapter/holder/BaseViewHolder.java
// public class BaseViewHolder extends RecyclerView.ViewHolder {
// public ViewHolderManager viewHolderManager;
// public Object itemData;
//
//
// public BaseViewHolder(View itemView) {
// super(itemView);
// }
//
//
// public Object getItemData() {
// return itemData;
// }
//
// /**
// * header和footer的个数也计算在内
// * {@link #getAdapterPosition()}
// */
// public int getItemPosition() {
// return getAdapterPosition();
// }
//
// public ViewHolderManager getViewHolderManager() {
// return viewHolderManager;
// }
//
// }
//
// Path: library/src/main/java/com/freelib/multiitem/adapter/holder/BaseViewHolderManager.java
// public abstract class BaseViewHolderManager<T> extends ViewHolderManager<T, BaseViewHolder> {
// @Override
// public abstract void onBindViewHolder(BaseViewHolder holder, T t);
//
// @NonNull
// @Override
// public BaseViewHolder onCreateViewHolder(@NonNull ViewGroup parent) {
// BaseViewHolder viewHolder = new BaseViewHolder(getItemView(parent));
// onCreateViewHolder(viewHolder);
// return viewHolder;
// }
//
// /**
// * {@link #onCreateViewHolder}
// */
// protected void onCreateViewHolder(@NonNull BaseViewHolder holder) {
// }
//
// }
//
// Path: demo/src/main/java/com/freelib/multiitem/demo/bean/TextDragBean.java
// public class TextDragBean extends BaseItemData implements ItemDrag {
// private String text;
// private boolean isCanMove = true;
// private boolean isCanChangeRecycler = true;
// private boolean isCanDrag = true;
//
// public TextDragBean(String text) {
// this.text = text;
// }
//
// public TextDragBean(String text, boolean isCanMove) {
// this.text = text;
// this.isCanMove = isCanMove;
// }
//
// public TextDragBean(String text, boolean isCanMove, boolean isCanChangeRecycler) {
// this.text = text;
// this.isCanMove = isCanMove;
// this.isCanChangeRecycler = isCanChangeRecycler;
// }
//
// public TextDragBean(String text, boolean isCanMove, boolean isCanChangeRecycler, boolean isCanDrag) {
// this.text = text;
// this.isCanMove = isCanMove;
// this.isCanChangeRecycler = isCanChangeRecycler;
// this.isCanDrag = isCanDrag;
// }
//
// public String getText() {
// return text;
// }
//
// public void setText(String text) {
// this.text = text;
// }
//
// @Override
// public String toString() {
// return text;
// }
//
// @Override
// public boolean isCanMove() {
// return isCanMove;
// }
//
// public void setCanMove(boolean canMove) {
// isCanMove = canMove;
// }
//
// @Override
// public boolean isCanChangeRecycler() {
// return isCanChangeRecycler;
// }
//
// public void setCanChangeRecycler(boolean canChangeRecycler) {
// isCanChangeRecycler = canChangeRecycler;
// }
//
// @Override
// public boolean isCanDrag() {
// return isCanDrag;
// }
//
// public void setCanDrag(boolean canDrag) {
// isCanDrag = canDrag;
// }
// }
// Path: demo/src/main/java/com/freelib/multiitem/demo/viewholder/TextViewDragManager.java
import android.support.annotation.NonNull;
import android.widget.TextView;
import com.freelib.multiitem.adapter.holder.BaseViewHolder;
import com.freelib.multiitem.adapter.holder.BaseViewHolderManager;
import com.freelib.multiitem.demo.R;
import com.freelib.multiitem.demo.bean.TextDragBean;
package com.freelib.multiitem.demo.viewholder;
/**
* @author free46000 2017/03/17
* @version v1.0
*/
public class TextViewDragManager extends BaseViewHolderManager<TextDragBean> {
@Override | public void onBindViewHolder(@NonNull BaseViewHolder holder, @NonNull TextDragBean data) { |
free46000/MultiItem | demo/src/main/java/com/freelib/multiitem/demo/viewholder/ReceiveMessageManager.java | // Path: library/src/main/java/com/freelib/multiitem/adapter/holder/BaseViewHolder.java
// public class BaseViewHolder extends RecyclerView.ViewHolder {
// public ViewHolderManager viewHolderManager;
// public Object itemData;
//
//
// public BaseViewHolder(View itemView) {
// super(itemView);
// }
//
//
// public Object getItemData() {
// return itemData;
// }
//
// /**
// * header和footer的个数也计算在内
// * {@link #getAdapterPosition()}
// */
// public int getItemPosition() {
// return getAdapterPosition();
// }
//
// public ViewHolderManager getViewHolderManager() {
// return viewHolderManager;
// }
//
// }
//
// Path: library/src/main/java/com/freelib/multiitem/adapter/holder/BaseViewHolderManager.java
// public abstract class BaseViewHolderManager<T> extends ViewHolderManager<T, BaseViewHolder> {
// @Override
// public abstract void onBindViewHolder(BaseViewHolder holder, T t);
//
// @NonNull
// @Override
// public BaseViewHolder onCreateViewHolder(@NonNull ViewGroup parent) {
// BaseViewHolder viewHolder = new BaseViewHolder(getItemView(parent));
// onCreateViewHolder(viewHolder);
// return viewHolder;
// }
//
// /**
// * {@link #onCreateViewHolder}
// */
// protected void onCreateViewHolder(@NonNull BaseViewHolder holder) {
// }
//
// }
//
// Path: demo/src/main/java/com/freelib/multiitem/demo/bean/MessageBean.java
// public class MessageBean {
// private String message;
// private String sender;
//
// public MessageBean(String message, String sender) {
// this.message = message;
// this.sender = sender;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// public String getSender() {
// return sender;
// }
//
// public void setSender(String sender) {
// this.sender = sender;
// }
// }
| import android.support.annotation.NonNull;
import android.widget.TextView;
import com.freelib.multiitem.adapter.holder.BaseViewHolder;
import com.freelib.multiitem.adapter.holder.BaseViewHolderManager;
import com.freelib.multiitem.demo.R;
import com.freelib.multiitem.demo.bean.MessageBean; | package com.freelib.multiitem.demo.viewholder;
/**
* @author free46000 2017/03/17
*/
public class ReceiveMessageManager extends BaseViewHolderManager<MessageBean> {
@Override | // Path: library/src/main/java/com/freelib/multiitem/adapter/holder/BaseViewHolder.java
// public class BaseViewHolder extends RecyclerView.ViewHolder {
// public ViewHolderManager viewHolderManager;
// public Object itemData;
//
//
// public BaseViewHolder(View itemView) {
// super(itemView);
// }
//
//
// public Object getItemData() {
// return itemData;
// }
//
// /**
// * header和footer的个数也计算在内
// * {@link #getAdapterPosition()}
// */
// public int getItemPosition() {
// return getAdapterPosition();
// }
//
// public ViewHolderManager getViewHolderManager() {
// return viewHolderManager;
// }
//
// }
//
// Path: library/src/main/java/com/freelib/multiitem/adapter/holder/BaseViewHolderManager.java
// public abstract class BaseViewHolderManager<T> extends ViewHolderManager<T, BaseViewHolder> {
// @Override
// public abstract void onBindViewHolder(BaseViewHolder holder, T t);
//
// @NonNull
// @Override
// public BaseViewHolder onCreateViewHolder(@NonNull ViewGroup parent) {
// BaseViewHolder viewHolder = new BaseViewHolder(getItemView(parent));
// onCreateViewHolder(viewHolder);
// return viewHolder;
// }
//
// /**
// * {@link #onCreateViewHolder}
// */
// protected void onCreateViewHolder(@NonNull BaseViewHolder holder) {
// }
//
// }
//
// Path: demo/src/main/java/com/freelib/multiitem/demo/bean/MessageBean.java
// public class MessageBean {
// private String message;
// private String sender;
//
// public MessageBean(String message, String sender) {
// this.message = message;
// this.sender = sender;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// public String getSender() {
// return sender;
// }
//
// public void setSender(String sender) {
// this.sender = sender;
// }
// }
// Path: demo/src/main/java/com/freelib/multiitem/demo/viewholder/ReceiveMessageManager.java
import android.support.annotation.NonNull;
import android.widget.TextView;
import com.freelib.multiitem.adapter.holder.BaseViewHolder;
import com.freelib.multiitem.adapter.holder.BaseViewHolderManager;
import com.freelib.multiitem.demo.R;
import com.freelib.multiitem.demo.bean.MessageBean;
package com.freelib.multiitem.demo.viewholder;
/**
* @author free46000 2017/03/17
*/
public class ReceiveMessageManager extends BaseViewHolderManager<MessageBean> {
@Override | public void onBindViewHolder(@NonNull BaseViewHolder holder, @NonNull MessageBean data) { |
free46000/MultiItem | library/src/main/java/com/freelib/multiitem/item/ItemInput.java | // Path: library/src/main/java/com/freelib/multiitem/adapter/holder/InputHolderManager.java
// public abstract class InputHolderManager<T extends ItemInput> extends BaseViewHolderManager<T> {
// protected Object originalValue;
// protected BaseViewHolder viewHolder;
//
// /**
// * 录入的key,和{@link #getValue()}一起组装为Map 如果为null则不组装 <br>
// * 如果是复杂的录入可以直接覆写{@link #getValueMap()}自己组装key-value Map
// *
// * @return 录入key
// */
// public abstract String getKey();
//
// /**
// * 录入的值,和{@link #getKey()}一起组装为Map 如果为null则不组装 <br>
// * 如果是复杂的录入可以直接覆写{@link #getValueMap()}自己组装key-value Map
// *
// * @return 录入值
// */
// public abstract Object getValue();
//
// @Override
// protected void onCreateViewHolder(@NonNull BaseViewHolder holder) {
// super.onCreateViewHolder(holder);
// initInputView(holder);
// originalValue = getValue();
// viewHolder = holder;
// }
//
// /**
// * 初始化Input视图,由于Input视图不可以复用,所以直接在初始化视图时设置好相关内容即可
// *
// * @param holder BaseViewHolder
// */
// protected abstract void initInputView(BaseViewHolder holder);
//
// @Deprecated
// @Override
// public void onBindViewHolder(BaseViewHolder holder, T t) {
// }
//
// @Deprecated
// @Override
// public void onBindViewHolder(@NonNull BaseViewHolder holder, @NonNull T t, @NonNull ViewHolderParams params) {
// super.onBindViewHolder(holder, t, params);
// }
//
// /**
// * 复杂业务可以覆写本方法,自定义返回多组key-value
// *
// * @return 录入的key-value Map
// */
// public Map<String, Object> getValueMap() {
// String key = getKey();
// Object value = getValue();
// if (key == null || value == null) {
// return null;
// }
// return Collections.singletonMap(key, value);
// }
//
// /**
// * 是否在初始化后发生改变,如用户手动更改<br>
// * 在{@link #initInputView(BaseViewHolder)}的时候会记录当时的value,然后调用本方法时去做对比
// *
// * @return true:已改变;false:未改变
// */
// public boolean isValueChange() {
// Object value = getValue();
// return value == null ? null != originalValue : !value.equals(originalValue);
// }
//
// /**
// * 是否验证有效,如Item不能为空
// *
// * @return true:有效;false:无效 默认true
// */
// public boolean isValueValid() {
// return true;
// }
//
//
// @Override
// public boolean isClickable() {
// return false;
// }
// }
| import com.freelib.multiitem.adapter.holder.InputHolderManager; | package com.freelib.multiitem.item;
/**
* 录入Input Item接口
* Created by free46000 on 2017/4/10.
*/
public interface ItemInput extends ItemManager {
/**
* 返回InputHolderManager
*
* @return InputHolderManager
* @see InputHolderManager
*/
@Override | // Path: library/src/main/java/com/freelib/multiitem/adapter/holder/InputHolderManager.java
// public abstract class InputHolderManager<T extends ItemInput> extends BaseViewHolderManager<T> {
// protected Object originalValue;
// protected BaseViewHolder viewHolder;
//
// /**
// * 录入的key,和{@link #getValue()}一起组装为Map 如果为null则不组装 <br>
// * 如果是复杂的录入可以直接覆写{@link #getValueMap()}自己组装key-value Map
// *
// * @return 录入key
// */
// public abstract String getKey();
//
// /**
// * 录入的值,和{@link #getKey()}一起组装为Map 如果为null则不组装 <br>
// * 如果是复杂的录入可以直接覆写{@link #getValueMap()}自己组装key-value Map
// *
// * @return 录入值
// */
// public abstract Object getValue();
//
// @Override
// protected void onCreateViewHolder(@NonNull BaseViewHolder holder) {
// super.onCreateViewHolder(holder);
// initInputView(holder);
// originalValue = getValue();
// viewHolder = holder;
// }
//
// /**
// * 初始化Input视图,由于Input视图不可以复用,所以直接在初始化视图时设置好相关内容即可
// *
// * @param holder BaseViewHolder
// */
// protected abstract void initInputView(BaseViewHolder holder);
//
// @Deprecated
// @Override
// public void onBindViewHolder(BaseViewHolder holder, T t) {
// }
//
// @Deprecated
// @Override
// public void onBindViewHolder(@NonNull BaseViewHolder holder, @NonNull T t, @NonNull ViewHolderParams params) {
// super.onBindViewHolder(holder, t, params);
// }
//
// /**
// * 复杂业务可以覆写本方法,自定义返回多组key-value
// *
// * @return 录入的key-value Map
// */
// public Map<String, Object> getValueMap() {
// String key = getKey();
// Object value = getValue();
// if (key == null || value == null) {
// return null;
// }
// return Collections.singletonMap(key, value);
// }
//
// /**
// * 是否在初始化后发生改变,如用户手动更改<br>
// * 在{@link #initInputView(BaseViewHolder)}的时候会记录当时的value,然后调用本方法时去做对比
// *
// * @return true:已改变;false:未改变
// */
// public boolean isValueChange() {
// Object value = getValue();
// return value == null ? null != originalValue : !value.equals(originalValue);
// }
//
// /**
// * 是否验证有效,如Item不能为空
// *
// * @return true:有效;false:无效 默认true
// */
// public boolean isValueValid() {
// return true;
// }
//
//
// @Override
// public boolean isClickable() {
// return false;
// }
// }
// Path: library/src/main/java/com/freelib/multiitem/item/ItemInput.java
import com.freelib.multiitem.adapter.holder.InputHolderManager;
package com.freelib.multiitem.item;
/**
* 录入Input Item接口
* Created by free46000 on 2017/4/10.
*/
public interface ItemInput extends ItemManager {
/**
* 返回InputHolderManager
*
* @return InputHolderManager
* @see InputHolderManager
*/
@Override | InputHolderManager getViewHolderManager(); |
free46000/MultiItem | library/src/main/java/com/freelib/multiitem/item/DataBindItemInput.java | // Path: library/src/main/java/com/freelib/multiitem/adapter/holder/BaseViewHolder.java
// public class BaseViewHolder extends RecyclerView.ViewHolder {
// public ViewHolderManager viewHolderManager;
// public Object itemData;
//
//
// public BaseViewHolder(View itemView) {
// super(itemView);
// }
//
//
// public Object getItemData() {
// return itemData;
// }
//
// /**
// * header和footer的个数也计算在内
// * {@link #getAdapterPosition()}
// */
// public int getItemPosition() {
// return getAdapterPosition();
// }
//
// public ViewHolderManager getViewHolderManager() {
// return viewHolderManager;
// }
//
// }
//
// Path: library/src/main/java/com/freelib/multiitem/adapter/holder/InputHolderManager.java
// public abstract class InputHolderManager<T extends ItemInput> extends BaseViewHolderManager<T> {
// protected Object originalValue;
// protected BaseViewHolder viewHolder;
//
// /**
// * 录入的key,和{@link #getValue()}一起组装为Map 如果为null则不组装 <br>
// * 如果是复杂的录入可以直接覆写{@link #getValueMap()}自己组装key-value Map
// *
// * @return 录入key
// */
// public abstract String getKey();
//
// /**
// * 录入的值,和{@link #getKey()}一起组装为Map 如果为null则不组装 <br>
// * 如果是复杂的录入可以直接覆写{@link #getValueMap()}自己组装key-value Map
// *
// * @return 录入值
// */
// public abstract Object getValue();
//
// @Override
// protected void onCreateViewHolder(@NonNull BaseViewHolder holder) {
// super.onCreateViewHolder(holder);
// initInputView(holder);
// originalValue = getValue();
// viewHolder = holder;
// }
//
// /**
// * 初始化Input视图,由于Input视图不可以复用,所以直接在初始化视图时设置好相关内容即可
// *
// * @param holder BaseViewHolder
// */
// protected abstract void initInputView(BaseViewHolder holder);
//
// @Deprecated
// @Override
// public void onBindViewHolder(BaseViewHolder holder, T t) {
// }
//
// @Deprecated
// @Override
// public void onBindViewHolder(@NonNull BaseViewHolder holder, @NonNull T t, @NonNull ViewHolderParams params) {
// super.onBindViewHolder(holder, t, params);
// }
//
// /**
// * 复杂业务可以覆写本方法,自定义返回多组key-value
// *
// * @return 录入的key-value Map
// */
// public Map<String, Object> getValueMap() {
// String key = getKey();
// Object value = getValue();
// if (key == null || value == null) {
// return null;
// }
// return Collections.singletonMap(key, value);
// }
//
// /**
// * 是否在初始化后发生改变,如用户手动更改<br>
// * 在{@link #initInputView(BaseViewHolder)}的时候会记录当时的value,然后调用本方法时去做对比
// *
// * @return true:已改变;false:未改变
// */
// public boolean isValueChange() {
// Object value = getValue();
// return value == null ? null != originalValue : !value.equals(originalValue);
// }
//
// /**
// * 是否验证有效,如Item不能为空
// *
// * @return true:有效;false:无效 默认true
// */
// public boolean isValueValid() {
// return true;
// }
//
//
// @Override
// public boolean isClickable() {
// return false;
// }
// }
| import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import com.freelib.multiitem.adapter.holder.BaseViewHolder;
import com.freelib.multiitem.adapter.holder.InputHolderManager; | package com.freelib.multiitem.item;
/**
* 数据绑定的录入Item
* Created by free46000 on 2017/4/16.
*/
public abstract class DataBindItemInput<T extends BaseItemInput> extends BaseItemInput<T> {
{
enableDataBind();
}
/**
* @param key 录入对应key
*/
public DataBindItemInput(String key) {
super(key);
}
@Override | // Path: library/src/main/java/com/freelib/multiitem/adapter/holder/BaseViewHolder.java
// public class BaseViewHolder extends RecyclerView.ViewHolder {
// public ViewHolderManager viewHolderManager;
// public Object itemData;
//
//
// public BaseViewHolder(View itemView) {
// super(itemView);
// }
//
//
// public Object getItemData() {
// return itemData;
// }
//
// /**
// * header和footer的个数也计算在内
// * {@link #getAdapterPosition()}
// */
// public int getItemPosition() {
// return getAdapterPosition();
// }
//
// public ViewHolderManager getViewHolderManager() {
// return viewHolderManager;
// }
//
// }
//
// Path: library/src/main/java/com/freelib/multiitem/adapter/holder/InputHolderManager.java
// public abstract class InputHolderManager<T extends ItemInput> extends BaseViewHolderManager<T> {
// protected Object originalValue;
// protected BaseViewHolder viewHolder;
//
// /**
// * 录入的key,和{@link #getValue()}一起组装为Map 如果为null则不组装 <br>
// * 如果是复杂的录入可以直接覆写{@link #getValueMap()}自己组装key-value Map
// *
// * @return 录入key
// */
// public abstract String getKey();
//
// /**
// * 录入的值,和{@link #getKey()}一起组装为Map 如果为null则不组装 <br>
// * 如果是复杂的录入可以直接覆写{@link #getValueMap()}自己组装key-value Map
// *
// * @return 录入值
// */
// public abstract Object getValue();
//
// @Override
// protected void onCreateViewHolder(@NonNull BaseViewHolder holder) {
// super.onCreateViewHolder(holder);
// initInputView(holder);
// originalValue = getValue();
// viewHolder = holder;
// }
//
// /**
// * 初始化Input视图,由于Input视图不可以复用,所以直接在初始化视图时设置好相关内容即可
// *
// * @param holder BaseViewHolder
// */
// protected abstract void initInputView(BaseViewHolder holder);
//
// @Deprecated
// @Override
// public void onBindViewHolder(BaseViewHolder holder, T t) {
// }
//
// @Deprecated
// @Override
// public void onBindViewHolder(@NonNull BaseViewHolder holder, @NonNull T t, @NonNull ViewHolderParams params) {
// super.onBindViewHolder(holder, t, params);
// }
//
// /**
// * 复杂业务可以覆写本方法,自定义返回多组key-value
// *
// * @return 录入的key-value Map
// */
// public Map<String, Object> getValueMap() {
// String key = getKey();
// Object value = getValue();
// if (key == null || value == null) {
// return null;
// }
// return Collections.singletonMap(key, value);
// }
//
// /**
// * 是否在初始化后发生改变,如用户手动更改<br>
// * 在{@link #initInputView(BaseViewHolder)}的时候会记录当时的value,然后调用本方法时去做对比
// *
// * @return true:已改变;false:未改变
// */
// public boolean isValueChange() {
// Object value = getValue();
// return value == null ? null != originalValue : !value.equals(originalValue);
// }
//
// /**
// * 是否验证有效,如Item不能为空
// *
// * @return true:有效;false:无效 默认true
// */
// public boolean isValueValid() {
// return true;
// }
//
//
// @Override
// public boolean isClickable() {
// return false;
// }
// }
// Path: library/src/main/java/com/freelib/multiitem/item/DataBindItemInput.java
import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import com.freelib.multiitem.adapter.holder.BaseViewHolder;
import com.freelib.multiitem.adapter.holder.InputHolderManager;
package com.freelib.multiitem.item;
/**
* 数据绑定的录入Item
* Created by free46000 on 2017/4/16.
*/
public abstract class DataBindItemInput<T extends BaseItemInput> extends BaseItemInput<T> {
{
enableDataBind();
}
/**
* @param key 录入对应key
*/
public DataBindItemInput(String key) {
super(key);
}
@Override | protected void initInputView(BaseViewHolder holder) { |
free46000/MultiItem | library/src/main/java/com/freelib/multiitem/listener/OnItemClickListener.java | // Path: library/src/main/java/com/freelib/multiitem/adapter/holder/BaseViewHolder.java
// public class BaseViewHolder extends RecyclerView.ViewHolder {
// public ViewHolderManager viewHolderManager;
// public Object itemData;
//
//
// public BaseViewHolder(View itemView) {
// super(itemView);
// }
//
//
// public Object getItemData() {
// return itemData;
// }
//
// /**
// * header和footer的个数也计算在内
// * {@link #getAdapterPosition()}
// */
// public int getItemPosition() {
// return getAdapterPosition();
// }
//
// public ViewHolderManager getViewHolderManager() {
// return viewHolderManager;
// }
//
// }
| import android.view.View;
import com.freelib.multiitem.adapter.holder.BaseViewHolder; | package com.freelib.multiitem.listener;
/**
* Item点击监听类
*
* @author free46000
*/
public abstract class OnItemClickListener implements View.OnClickListener {
@Override
public void onClick(View v) { | // Path: library/src/main/java/com/freelib/multiitem/adapter/holder/BaseViewHolder.java
// public class BaseViewHolder extends RecyclerView.ViewHolder {
// public ViewHolderManager viewHolderManager;
// public Object itemData;
//
//
// public BaseViewHolder(View itemView) {
// super(itemView);
// }
//
//
// public Object getItemData() {
// return itemData;
// }
//
// /**
// * header和footer的个数也计算在内
// * {@link #getAdapterPosition()}
// */
// public int getItemPosition() {
// return getAdapterPosition();
// }
//
// public ViewHolderManager getViewHolderManager() {
// return viewHolderManager;
// }
//
// }
// Path: library/src/main/java/com/freelib/multiitem/listener/OnItemClickListener.java
import android.view.View;
import com.freelib.multiitem.adapter.holder.BaseViewHolder;
package com.freelib.multiitem.listener;
/**
* Item点击监听类
*
* @author free46000
*/
public abstract class OnItemClickListener implements View.OnClickListener {
@Override
public void onClick(View v) { | BaseViewHolder viewHolder = ListenerUtil.getViewHolderByItemView(v); |
free46000/MultiItem | demo/src/main/java/com/freelib/multiitem/demo/viewholder/TextViewManager.java | // Path: library/src/main/java/com/freelib/multiitem/adapter/holder/BaseViewHolder.java
// public class BaseViewHolder extends RecyclerView.ViewHolder {
// public ViewHolderManager viewHolderManager;
// public Object itemData;
//
//
// public BaseViewHolder(View itemView) {
// super(itemView);
// }
//
//
// public Object getItemData() {
// return itemData;
// }
//
// /**
// * header和footer的个数也计算在内
// * {@link #getAdapterPosition()}
// */
// public int getItemPosition() {
// return getAdapterPosition();
// }
//
// public ViewHolderManager getViewHolderManager() {
// return viewHolderManager;
// }
//
// }
//
// Path: library/src/main/java/com/freelib/multiitem/adapter/holder/BaseViewHolderManager.java
// public abstract class BaseViewHolderManager<T> extends ViewHolderManager<T, BaseViewHolder> {
// @Override
// public abstract void onBindViewHolder(BaseViewHolder holder, T t);
//
// @NonNull
// @Override
// public BaseViewHolder onCreateViewHolder(@NonNull ViewGroup parent) {
// BaseViewHolder viewHolder = new BaseViewHolder(getItemView(parent));
// onCreateViewHolder(viewHolder);
// return viewHolder;
// }
//
// /**
// * {@link #onCreateViewHolder}
// */
// protected void onCreateViewHolder(@NonNull BaseViewHolder holder) {
// }
//
// }
//
// Path: demo/src/main/java/com/freelib/multiitem/demo/bean/TextBean.java
// public class TextBean {
// private String text;
//
// public TextBean(String text) {
// this.text = text;
// }
//
// public String getText() {
// return text;
// }
//
// public void setText(String text) {
// this.text = text;
// }
//
// @Override
// public String toString() {
// return text;
// }
// }
| import android.support.annotation.NonNull;
import android.widget.TextView;
import com.freelib.multiitem.adapter.holder.BaseViewHolder;
import com.freelib.multiitem.adapter.holder.BaseViewHolderManager;
import com.freelib.multiitem.demo.R;
import com.freelib.multiitem.demo.bean.TextBean; | package com.freelib.multiitem.demo.viewholder;
/**
* @author free46000 2017/03/17
* @version v1.0
*/
public class TextViewManager<T extends TextBean> extends BaseViewHolderManager<T> {
@Override | // Path: library/src/main/java/com/freelib/multiitem/adapter/holder/BaseViewHolder.java
// public class BaseViewHolder extends RecyclerView.ViewHolder {
// public ViewHolderManager viewHolderManager;
// public Object itemData;
//
//
// public BaseViewHolder(View itemView) {
// super(itemView);
// }
//
//
// public Object getItemData() {
// return itemData;
// }
//
// /**
// * header和footer的个数也计算在内
// * {@link #getAdapterPosition()}
// */
// public int getItemPosition() {
// return getAdapterPosition();
// }
//
// public ViewHolderManager getViewHolderManager() {
// return viewHolderManager;
// }
//
// }
//
// Path: library/src/main/java/com/freelib/multiitem/adapter/holder/BaseViewHolderManager.java
// public abstract class BaseViewHolderManager<T> extends ViewHolderManager<T, BaseViewHolder> {
// @Override
// public abstract void onBindViewHolder(BaseViewHolder holder, T t);
//
// @NonNull
// @Override
// public BaseViewHolder onCreateViewHolder(@NonNull ViewGroup parent) {
// BaseViewHolder viewHolder = new BaseViewHolder(getItemView(parent));
// onCreateViewHolder(viewHolder);
// return viewHolder;
// }
//
// /**
// * {@link #onCreateViewHolder}
// */
// protected void onCreateViewHolder(@NonNull BaseViewHolder holder) {
// }
//
// }
//
// Path: demo/src/main/java/com/freelib/multiitem/demo/bean/TextBean.java
// public class TextBean {
// private String text;
//
// public TextBean(String text) {
// this.text = text;
// }
//
// public String getText() {
// return text;
// }
//
// public void setText(String text) {
// this.text = text;
// }
//
// @Override
// public String toString() {
// return text;
// }
// }
// Path: demo/src/main/java/com/freelib/multiitem/demo/viewholder/TextViewManager.java
import android.support.annotation.NonNull;
import android.widget.TextView;
import com.freelib.multiitem.adapter.holder.BaseViewHolder;
import com.freelib.multiitem.adapter.holder.BaseViewHolderManager;
import com.freelib.multiitem.demo.R;
import com.freelib.multiitem.demo.bean.TextBean;
package com.freelib.multiitem.demo.viewholder;
/**
* @author free46000 2017/03/17
* @version v1.0
*/
public class TextViewManager<T extends TextBean> extends BaseViewHolderManager<T> {
@Override | public void onBindViewHolder(@NonNull BaseViewHolder holder, @NonNull T data) { |
free46000/MultiItem | library/src/main/java/com/freelib/multiitem/listener/OnItemLongClickListener.java | // Path: library/src/main/java/com/freelib/multiitem/adapter/holder/BaseViewHolder.java
// public class BaseViewHolder extends RecyclerView.ViewHolder {
// public ViewHolderManager viewHolderManager;
// public Object itemData;
//
//
// public BaseViewHolder(View itemView) {
// super(itemView);
// }
//
//
// public Object getItemData() {
// return itemData;
// }
//
// /**
// * header和footer的个数也计算在内
// * {@link #getAdapterPosition()}
// */
// public int getItemPosition() {
// return getAdapterPosition();
// }
//
// public ViewHolderManager getViewHolderManager() {
// return viewHolderManager;
// }
//
// }
| import android.view.View;
import com.freelib.multiitem.adapter.holder.BaseViewHolder; | package com.freelib.multiitem.listener;
/**
* Item长按监听类
*
* @author free46000
*/
public abstract class OnItemLongClickListener implements View.OnLongClickListener {
@Override
public boolean onLongClick(View v) { | // Path: library/src/main/java/com/freelib/multiitem/adapter/holder/BaseViewHolder.java
// public class BaseViewHolder extends RecyclerView.ViewHolder {
// public ViewHolderManager viewHolderManager;
// public Object itemData;
//
//
// public BaseViewHolder(View itemView) {
// super(itemView);
// }
//
//
// public Object getItemData() {
// return itemData;
// }
//
// /**
// * header和footer的个数也计算在内
// * {@link #getAdapterPosition()}
// */
// public int getItemPosition() {
// return getAdapterPosition();
// }
//
// public ViewHolderManager getViewHolderManager() {
// return viewHolderManager;
// }
//
// }
// Path: library/src/main/java/com/freelib/multiitem/listener/OnItemLongClickListener.java
import android.view.View;
import com.freelib.multiitem.adapter.holder.BaseViewHolder;
package com.freelib.multiitem.listener;
/**
* Item长按监听类
*
* @author free46000
*/
public abstract class OnItemLongClickListener implements View.OnLongClickListener {
@Override
public boolean onLongClick(View v) { | BaseViewHolder viewHolder = ListenerUtil.getViewHolderByItemView(v); |
free46000/MultiItem | demo/src/main/java/com/freelib/multiitem/demo/input/ItemNameAndSex.java | // Path: library/src/main/java/com/freelib/multiitem/adapter/holder/BaseViewHolder.java
// public class BaseViewHolder extends RecyclerView.ViewHolder {
// public ViewHolderManager viewHolderManager;
// public Object itemData;
//
//
// public BaseViewHolder(View itemView) {
// super(itemView);
// }
//
//
// public Object getItemData() {
// return itemData;
// }
//
// /**
// * header和footer的个数也计算在内
// * {@link #getAdapterPosition()}
// */
// public int getItemPosition() {
// return getAdapterPosition();
// }
//
// public ViewHolderManager getViewHolderManager() {
// return viewHolderManager;
// }
//
// }
//
// Path: library/src/main/java/com/freelib/multiitem/item/BaseItemInput.java
// public abstract class BaseItemInput<T extends BaseItemInput> extends InputHolderManager<T> implements ItemInput {
// protected String key;
//
// /**
// * @param key 录入对应key
// */
// public BaseItemInput(String key) {
// this.key = key;
// }
//
//
// @NonNull
// @Override
// public String getItemTypeName() {
// return toString();
// }
//
// @Override
// public InputHolderManager getViewHolderManager() {
// return this;
// }
//
// @Override
// public String getKey() {
// return key;
// }
//
// }
| import android.text.TextUtils;
import android.widget.EditText;
import android.widget.RadioGroup;
import com.freelib.multiitem.adapter.holder.BaseViewHolder;
import com.freelib.multiitem.demo.R;
import com.freelib.multiitem.item.BaseItemInput;
import java.util.HashMap;
import java.util.Map; | //在本方法中返回两个值的组合,作用是为判断表单的值是否被改变提供依据
//也可以直接覆写isValueChange()方法达到定制化
if (nameEdit == null) {
return null;
}
return nameEdit.getText().toString() + sexRadio.getCheckedRadioButtonId();
}
@Override
public boolean isValueValid() {
//如果名字输入框录入的值不为空则有效;其它无效
return nameEdit != null && !TextUtils.isEmpty(nameEdit.getText().toString());
}
@Override
public Map<String, Object> getValueMap() {
if (nameEdit == null) {
return null;
}
//此处自己组装Map{name:name,sex:sex}并返回,这样可以达到一个Item返回两组值的效果
Map<String, Object> valueMap = new HashMap<>(2);
valueMap.put("name", nameEdit.getText().toString());
int sexStrResId = sexRadio.getCheckedRadioButtonId() == R.id.man ? R.string.man : R.string.woman;
valueMap.put("sex", nameEdit.getContext().getString(sexStrResId));
return valueMap;
}
@Override | // Path: library/src/main/java/com/freelib/multiitem/adapter/holder/BaseViewHolder.java
// public class BaseViewHolder extends RecyclerView.ViewHolder {
// public ViewHolderManager viewHolderManager;
// public Object itemData;
//
//
// public BaseViewHolder(View itemView) {
// super(itemView);
// }
//
//
// public Object getItemData() {
// return itemData;
// }
//
// /**
// * header和footer的个数也计算在内
// * {@link #getAdapterPosition()}
// */
// public int getItemPosition() {
// return getAdapterPosition();
// }
//
// public ViewHolderManager getViewHolderManager() {
// return viewHolderManager;
// }
//
// }
//
// Path: library/src/main/java/com/freelib/multiitem/item/BaseItemInput.java
// public abstract class BaseItemInput<T extends BaseItemInput> extends InputHolderManager<T> implements ItemInput {
// protected String key;
//
// /**
// * @param key 录入对应key
// */
// public BaseItemInput(String key) {
// this.key = key;
// }
//
//
// @NonNull
// @Override
// public String getItemTypeName() {
// return toString();
// }
//
// @Override
// public InputHolderManager getViewHolderManager() {
// return this;
// }
//
// @Override
// public String getKey() {
// return key;
// }
//
// }
// Path: demo/src/main/java/com/freelib/multiitem/demo/input/ItemNameAndSex.java
import android.text.TextUtils;
import android.widget.EditText;
import android.widget.RadioGroup;
import com.freelib.multiitem.adapter.holder.BaseViewHolder;
import com.freelib.multiitem.demo.R;
import com.freelib.multiitem.item.BaseItemInput;
import java.util.HashMap;
import java.util.Map;
//在本方法中返回两个值的组合,作用是为判断表单的值是否被改变提供依据
//也可以直接覆写isValueChange()方法达到定制化
if (nameEdit == null) {
return null;
}
return nameEdit.getText().toString() + sexRadio.getCheckedRadioButtonId();
}
@Override
public boolean isValueValid() {
//如果名字输入框录入的值不为空则有效;其它无效
return nameEdit != null && !TextUtils.isEmpty(nameEdit.getText().toString());
}
@Override
public Map<String, Object> getValueMap() {
if (nameEdit == null) {
return null;
}
//此处自己组装Map{name:name,sex:sex}并返回,这样可以达到一个Item返回两组值的效果
Map<String, Object> valueMap = new HashMap<>(2);
valueMap.put("name", nameEdit.getText().toString());
int sexStrResId = sexRadio.getCheckedRadioButtonId() == R.id.man ? R.string.man : R.string.woman;
valueMap.put("sex", nameEdit.getContext().getString(sexStrResId));
return valueMap;
}
@Override | protected void initInputView(BaseViewHolder holder) { |
l0rdn1kk0n/wicket-jquery-selectors | src/main/java/de/agilecoders/wicket/jquery/WicketJquerySelectors.java | // Path: src/main/java/de/agilecoders/wicket/jquery/settings/IWicketJquerySelectorsSettings.java
// public interface IWicketJquerySelectorsSettings {
//
// /**
// * @return object mapper factory
// */
// ObjectMapperFactory getObjectMapperFactory();
// }
//
// Path: src/main/java/de/agilecoders/wicket/jquery/settings/WicketJquerySelectorsSettings.java
// public class WicketJquerySelectorsSettings implements IWicketJquerySelectorsSettings {
//
// private ObjectMapperFactory objectMapperFactory;
//
// /**
// * Construct.
// */
// public WicketJquerySelectorsSettings() {
// objectMapperFactory = new SingletonObjectMapperFactory();
// }
//
// /**
// * @return object mapper factory
// */
// @Override
// public ObjectMapperFactory getObjectMapperFactory() {
// return objectMapperFactory;
// }
//
// /**
// * sets the object mapper factory
// *
// * @param objectMapperFactory the object mapper factory to use for json serialization
// * @return this instance for chaining
// */
// public WicketJquerySelectorsSettings setObjectMapperFactory(ObjectMapperFactory objectMapperFactory) {
// this.objectMapperFactory = objectMapperFactory;
// return this;
// }
// }
| import de.agilecoders.wicket.jquery.settings.IWicketJquerySelectorsSettings;
import de.agilecoders.wicket.jquery.settings.WicketJquerySelectorsSettings;
import org.apache.wicket.Application;
import org.apache.wicket.MetaDataKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | package de.agilecoders.wicket.jquery;
/**
* base wicket-jquery-selectors class that is responsible for installation of custom settings.
*
* @author Michael Haitz <[email protected]>
*/
public final class WicketJquerySelectors {
private static final Logger LOG = LoggerFactory.getLogger("wicket-jquery-selectors");
/**
* The {@link org.apache.wicket.MetaDataKey} used to retrieve the {@link de.agilecoders.wicket.jquery.settings.IWicketJquerySelectorsSettings}
* from the Wicket {@link Appendable}.
*/ | // Path: src/main/java/de/agilecoders/wicket/jquery/settings/IWicketJquerySelectorsSettings.java
// public interface IWicketJquerySelectorsSettings {
//
// /**
// * @return object mapper factory
// */
// ObjectMapperFactory getObjectMapperFactory();
// }
//
// Path: src/main/java/de/agilecoders/wicket/jquery/settings/WicketJquerySelectorsSettings.java
// public class WicketJquerySelectorsSettings implements IWicketJquerySelectorsSettings {
//
// private ObjectMapperFactory objectMapperFactory;
//
// /**
// * Construct.
// */
// public WicketJquerySelectorsSettings() {
// objectMapperFactory = new SingletonObjectMapperFactory();
// }
//
// /**
// * @return object mapper factory
// */
// @Override
// public ObjectMapperFactory getObjectMapperFactory() {
// return objectMapperFactory;
// }
//
// /**
// * sets the object mapper factory
// *
// * @param objectMapperFactory the object mapper factory to use for json serialization
// * @return this instance for chaining
// */
// public WicketJquerySelectorsSettings setObjectMapperFactory(ObjectMapperFactory objectMapperFactory) {
// this.objectMapperFactory = objectMapperFactory;
// return this;
// }
// }
// Path: src/main/java/de/agilecoders/wicket/jquery/WicketJquerySelectors.java
import de.agilecoders.wicket.jquery.settings.IWicketJquerySelectorsSettings;
import de.agilecoders.wicket.jquery.settings.WicketJquerySelectorsSettings;
import org.apache.wicket.Application;
import org.apache.wicket.MetaDataKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
package de.agilecoders.wicket.jquery;
/**
* base wicket-jquery-selectors class that is responsible for installation of custom settings.
*
* @author Michael Haitz <[email protected]>
*/
public final class WicketJquerySelectors {
private static final Logger LOG = LoggerFactory.getLogger("wicket-jquery-selectors");
/**
* The {@link org.apache.wicket.MetaDataKey} used to retrieve the {@link de.agilecoders.wicket.jquery.settings.IWicketJquerySelectorsSettings}
* from the Wicket {@link Appendable}.
*/ | private static final MetaDataKey<IWicketJquerySelectorsSettings> JQUERY_SELECTORS_SETTINGS_METADATA_KEY = new MetaDataKey<IWicketJquerySelectorsSettings>() { |
l0rdn1kk0n/wicket-jquery-selectors | src/main/java/de/agilecoders/wicket/jquery/WicketJquerySelectors.java | // Path: src/main/java/de/agilecoders/wicket/jquery/settings/IWicketJquerySelectorsSettings.java
// public interface IWicketJquerySelectorsSettings {
//
// /**
// * @return object mapper factory
// */
// ObjectMapperFactory getObjectMapperFactory();
// }
//
// Path: src/main/java/de/agilecoders/wicket/jquery/settings/WicketJquerySelectorsSettings.java
// public class WicketJquerySelectorsSettings implements IWicketJquerySelectorsSettings {
//
// private ObjectMapperFactory objectMapperFactory;
//
// /**
// * Construct.
// */
// public WicketJquerySelectorsSettings() {
// objectMapperFactory = new SingletonObjectMapperFactory();
// }
//
// /**
// * @return object mapper factory
// */
// @Override
// public ObjectMapperFactory getObjectMapperFactory() {
// return objectMapperFactory;
// }
//
// /**
// * sets the object mapper factory
// *
// * @param objectMapperFactory the object mapper factory to use for json serialization
// * @return this instance for chaining
// */
// public WicketJquerySelectorsSettings setObjectMapperFactory(ObjectMapperFactory objectMapperFactory) {
// this.objectMapperFactory = objectMapperFactory;
// return this;
// }
// }
| import de.agilecoders.wicket.jquery.settings.IWicketJquerySelectorsSettings;
import de.agilecoders.wicket.jquery.settings.WicketJquerySelectorsSettings;
import org.apache.wicket.Application;
import org.apache.wicket.MetaDataKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | package de.agilecoders.wicket.jquery;
/**
* base wicket-jquery-selectors class that is responsible for installation of custom settings.
*
* @author Michael Haitz <[email protected]>
*/
public final class WicketJquerySelectors {
private static final Logger LOG = LoggerFactory.getLogger("wicket-jquery-selectors");
/**
* The {@link org.apache.wicket.MetaDataKey} used to retrieve the {@link de.agilecoders.wicket.jquery.settings.IWicketJquerySelectorsSettings}
* from the Wicket {@link Appendable}.
*/
private static final MetaDataKey<IWicketJquerySelectorsSettings> JQUERY_SELECTORS_SETTINGS_METADATA_KEY = new MetaDataKey<IWicketJquerySelectorsSettings>() {
};
/**
* Checks whether this library support is already installed
*
* @param application the wicket application
* @return {@code true} if library is already installed, otherwise {@code false}
*/
public static boolean isInstalled(Application application) {
return application != null && application.getMetaData(JQUERY_SELECTORS_SETTINGS_METADATA_KEY) != null;
}
/**
* installs the library to given application
*
* @param app the wicket application
*/
public static void install(final Application app) {
install(app, null);
}
/**
* installs the library settings to given app.
*
* @param app the wicket application
* @param settings the settings to use
*/
public static void install(Application app, IWicketJquerySelectorsSettings settings) {
final IWicketJquerySelectorsSettings existingSettings = settings(app);
if (existingSettings == null) {
if (settings == null) { | // Path: src/main/java/de/agilecoders/wicket/jquery/settings/IWicketJquerySelectorsSettings.java
// public interface IWicketJquerySelectorsSettings {
//
// /**
// * @return object mapper factory
// */
// ObjectMapperFactory getObjectMapperFactory();
// }
//
// Path: src/main/java/de/agilecoders/wicket/jquery/settings/WicketJquerySelectorsSettings.java
// public class WicketJquerySelectorsSettings implements IWicketJquerySelectorsSettings {
//
// private ObjectMapperFactory objectMapperFactory;
//
// /**
// * Construct.
// */
// public WicketJquerySelectorsSettings() {
// objectMapperFactory = new SingletonObjectMapperFactory();
// }
//
// /**
// * @return object mapper factory
// */
// @Override
// public ObjectMapperFactory getObjectMapperFactory() {
// return objectMapperFactory;
// }
//
// /**
// * sets the object mapper factory
// *
// * @param objectMapperFactory the object mapper factory to use for json serialization
// * @return this instance for chaining
// */
// public WicketJquerySelectorsSettings setObjectMapperFactory(ObjectMapperFactory objectMapperFactory) {
// this.objectMapperFactory = objectMapperFactory;
// return this;
// }
// }
// Path: src/main/java/de/agilecoders/wicket/jquery/WicketJquerySelectors.java
import de.agilecoders.wicket.jquery.settings.IWicketJquerySelectorsSettings;
import de.agilecoders.wicket.jquery.settings.WicketJquerySelectorsSettings;
import org.apache.wicket.Application;
import org.apache.wicket.MetaDataKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
package de.agilecoders.wicket.jquery;
/**
* base wicket-jquery-selectors class that is responsible for installation of custom settings.
*
* @author Michael Haitz <[email protected]>
*/
public final class WicketJquerySelectors {
private static final Logger LOG = LoggerFactory.getLogger("wicket-jquery-selectors");
/**
* The {@link org.apache.wicket.MetaDataKey} used to retrieve the {@link de.agilecoders.wicket.jquery.settings.IWicketJquerySelectorsSettings}
* from the Wicket {@link Appendable}.
*/
private static final MetaDataKey<IWicketJquerySelectorsSettings> JQUERY_SELECTORS_SETTINGS_METADATA_KEY = new MetaDataKey<IWicketJquerySelectorsSettings>() {
};
/**
* Checks whether this library support is already installed
*
* @param application the wicket application
* @return {@code true} if library is already installed, otherwise {@code false}
*/
public static boolean isInstalled(Application application) {
return application != null && application.getMetaData(JQUERY_SELECTORS_SETTINGS_METADATA_KEY) != null;
}
/**
* installs the library to given application
*
* @param app the wicket application
*/
public static void install(final Application app) {
install(app, null);
}
/**
* installs the library settings to given app.
*
* @param app the wicket application
* @param settings the settings to use
*/
public static void install(Application app, IWicketJquerySelectorsSettings settings) {
final IWicketJquerySelectorsSettings existingSettings = settings(app);
if (existingSettings == null) {
if (settings == null) { | settings = new WicketJquerySelectorsSettings(); |
l0rdn1kk0n/wicket-jquery-selectors | src/main/java/de/agilecoders/wicket/jquery/function/JavaScriptInlineFunction.java | // Path: src/main/java/de/agilecoders/wicket/jquery/util/Strings2.java
// public static String nullToEmpty(final String value) {
// return value != null ? value : "";
// }
| import org.apache.wicket.util.lang.Objects;
import java.util.ArrayList;
import java.util.List;
import static de.agilecoders.wicket.jquery.util.Strings2.nullToEmpty; | package de.agilecoders.wicket.jquery.function;
/**
* simple class to represent a javascript function.
*/
public class JavaScriptInlineFunction extends AbstractFunction {
private final String functionBody;
/**
* Construct.
*
* @param functionBody the function body as string
*/
public JavaScriptInlineFunction(final String functionBody) {
this(functionBody, new ArrayList());
}
/**
* Construct.
*
* @param functionBody the function body as string
*/
public JavaScriptInlineFunction(final String functionBody, final List<CharSequence> parameters) {
super("function", parameters);
| // Path: src/main/java/de/agilecoders/wicket/jquery/util/Strings2.java
// public static String nullToEmpty(final String value) {
// return value != null ? value : "";
// }
// Path: src/main/java/de/agilecoders/wicket/jquery/function/JavaScriptInlineFunction.java
import org.apache.wicket.util.lang.Objects;
import java.util.ArrayList;
import java.util.List;
import static de.agilecoders.wicket.jquery.util.Strings2.nullToEmpty;
package de.agilecoders.wicket.jquery.function;
/**
* simple class to represent a javascript function.
*/
public class JavaScriptInlineFunction extends AbstractFunction {
private final String functionBody;
/**
* Construct.
*
* @param functionBody the function body as string
*/
public JavaScriptInlineFunction(final String functionBody) {
this(functionBody, new ArrayList());
}
/**
* Construct.
*
* @param functionBody the function body as string
*/
public JavaScriptInlineFunction(final String functionBody, final List<CharSequence> parameters) {
super("function", parameters);
| this.functionBody = nullToEmpty(functionBody); |
l0rdn1kk0n/wicket-jquery-selectors | src/test/java/de/agilecoders/wicket/jquery/function/ConfigurableFunctionTest.java | // Path: src/test/java/de/agilecoders/wicket/jquery/SimpleConfig.java
// public class SimpleConfig extends AbstractConfig {
// private static final IKey<String> string = newKey("string", null);
// private static final IKey<Integer> integer = newKey("integer", null);
//
// public SimpleConfig() {
// put(string, "1");
// put(integer, 1);
// }
// }
| import de.agilecoders.wicket.jquery.SimpleConfig;
import org.junit.Assert;
import org.junit.Test;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is; | package de.agilecoders.wicket.jquery.function;
public class ConfigurableFunctionTest extends Assert {
@Test
public void one() { | // Path: src/test/java/de/agilecoders/wicket/jquery/SimpleConfig.java
// public class SimpleConfig extends AbstractConfig {
// private static final IKey<String> string = newKey("string", null);
// private static final IKey<Integer> integer = newKey("integer", null);
//
// public SimpleConfig() {
// put(string, "1");
// put(integer, 1);
// }
// }
// Path: src/test/java/de/agilecoders/wicket/jquery/function/ConfigurableFunctionTest.java
import de.agilecoders.wicket.jquery.SimpleConfig;
import org.junit.Assert;
import org.junit.Test;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
package de.agilecoders.wicket.jquery.function;
public class ConfigurableFunctionTest extends Assert {
@Test
public void one() { | ConfigurableFunction function = new ConfigurableFunction("fName", new SimpleConfig()); |
l0rdn1kk0n/wicket-jquery-selectors | src/main/java/de/agilecoders/wicket/jquery/util/Json.java | // Path: src/main/java/de/agilecoders/wicket/jquery/WicketJquerySelectors.java
// public final class WicketJquerySelectors {
// private static final Logger LOG = LoggerFactory.getLogger("wicket-jquery-selectors");
//
// /**
// * The {@link org.apache.wicket.MetaDataKey} used to retrieve the {@link de.agilecoders.wicket.jquery.settings.IWicketJquerySelectorsSettings}
// * from the Wicket {@link Appendable}.
// */
// private static final MetaDataKey<IWicketJquerySelectorsSettings> JQUERY_SELECTORS_SETTINGS_METADATA_KEY = new MetaDataKey<IWicketJquerySelectorsSettings>() {
// };
//
// /**
// * Checks whether this library support is already installed
// *
// * @param application the wicket application
// * @return {@code true} if library is already installed, otherwise {@code false}
// */
// public static boolean isInstalled(Application application) {
// return application != null && application.getMetaData(JQUERY_SELECTORS_SETTINGS_METADATA_KEY) != null;
// }
// /**
// * installs the library to given application
// *
// * @param app the wicket application
// */
// public static void install(final Application app) {
// install(app, null);
// }
//
// /**
// * installs the library settings to given app.
// *
// * @param app the wicket application
// * @param settings the settings to use
// */
// public static void install(Application app, IWicketJquerySelectorsSettings settings) {
// final IWicketJquerySelectorsSettings existingSettings = settings(app);
//
// if (existingSettings == null) {
// if (settings == null) {
// settings = new WicketJquerySelectorsSettings();
// }
//
// app.setMetaData(JQUERY_SELECTORS_SETTINGS_METADATA_KEY, settings);
//
// LOG.info("initialize wicket jquery selectors with given settings: {}", settings);
// }
// }
//
// /**
// * returns the {@link IWicketJquerySelectorsSettings} which are assigned to given application
// *
// * @param app The current application
// * @return assigned {@link IWicketJquerySelectorsSettings}
// */
// public static IWicketJquerySelectorsSettings settings(final Application app) {
// return app.getMetaData(JQUERY_SELECTORS_SETTINGS_METADATA_KEY);
// }
//
// /**
// * returns the {@link IWicketJquerySelectorsSettings} which are assigned to given application or a new default instance.
// *
// * This is an internal API method, please don't use it.
// *
// * @return assigned {@link IWicketJquerySelectorsSettings}
// */
// public static IWicketJquerySelectorsSettings assignedSettingsOrDefault() {
// Application app = Application.exists() ? Application.get() : null;
//
// if (isInstalled(app)) {
// return settings();
// } else {
// LOG.info("try to get settings, but WicketJquerySelectors wasn't installed to current application. Fallback to default settings.");
//
// return new WicketJquerySelectorsSettings();
// }
// }
//
// /**
// * returns the {@link IWicketJquerySelectorsSettings} which are assigned to current application
// *
// * @return assigned {@link IWicketJquerySelectorsSettings}
// */
// public static IWicketJquerySelectorsSettings settings() {
// if (Application.exists()) {
// final IWicketJquerySelectorsSettings settings = Application.get().getMetaData(JQUERY_SELECTORS_SETTINGS_METADATA_KEY);
//
// if (settings != null) {
// return settings;
// } else {
// throw new IllegalStateException("you have to call WicketJquerySelectors.install()");
// }
// }
//
// throw new IllegalStateException("there is no active application assigned to this thread.");
// }
//
// /**
// * private constructor.
// */
// private WicketJquerySelectors() {
// throw new UnsupportedOperationException();
// }
// }
//
// Path: src/main/java/de/agilecoders/wicket/jquery/settings/ObjectMapperFactory.java
// public interface ObjectMapperFactory {
//
// /**
// * @return new object mapper instance
// */
// ObjectMapper newObjectMapper();
// }
| import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import de.agilecoders.wicket.jquery.WicketJquerySelectors;
import de.agilecoders.wicket.jquery.settings.ObjectMapperFactory;
import org.apache.wicket.util.io.IClusterable;
import org.apache.wicket.util.lang.Args;
import org.apache.wicket.util.string.Strings; | package de.agilecoders.wicket.jquery.util;
/**
* Helper functions to handle JsonNode values.
*
* @author miha
*/
public final class Json {
/**
* lazy holder to give application the chance to install its own
*/
private static final class Holder { | // Path: src/main/java/de/agilecoders/wicket/jquery/WicketJquerySelectors.java
// public final class WicketJquerySelectors {
// private static final Logger LOG = LoggerFactory.getLogger("wicket-jquery-selectors");
//
// /**
// * The {@link org.apache.wicket.MetaDataKey} used to retrieve the {@link de.agilecoders.wicket.jquery.settings.IWicketJquerySelectorsSettings}
// * from the Wicket {@link Appendable}.
// */
// private static final MetaDataKey<IWicketJquerySelectorsSettings> JQUERY_SELECTORS_SETTINGS_METADATA_KEY = new MetaDataKey<IWicketJquerySelectorsSettings>() {
// };
//
// /**
// * Checks whether this library support is already installed
// *
// * @param application the wicket application
// * @return {@code true} if library is already installed, otherwise {@code false}
// */
// public static boolean isInstalled(Application application) {
// return application != null && application.getMetaData(JQUERY_SELECTORS_SETTINGS_METADATA_KEY) != null;
// }
// /**
// * installs the library to given application
// *
// * @param app the wicket application
// */
// public static void install(final Application app) {
// install(app, null);
// }
//
// /**
// * installs the library settings to given app.
// *
// * @param app the wicket application
// * @param settings the settings to use
// */
// public static void install(Application app, IWicketJquerySelectorsSettings settings) {
// final IWicketJquerySelectorsSettings existingSettings = settings(app);
//
// if (existingSettings == null) {
// if (settings == null) {
// settings = new WicketJquerySelectorsSettings();
// }
//
// app.setMetaData(JQUERY_SELECTORS_SETTINGS_METADATA_KEY, settings);
//
// LOG.info("initialize wicket jquery selectors with given settings: {}", settings);
// }
// }
//
// /**
// * returns the {@link IWicketJquerySelectorsSettings} which are assigned to given application
// *
// * @param app The current application
// * @return assigned {@link IWicketJquerySelectorsSettings}
// */
// public static IWicketJquerySelectorsSettings settings(final Application app) {
// return app.getMetaData(JQUERY_SELECTORS_SETTINGS_METADATA_KEY);
// }
//
// /**
// * returns the {@link IWicketJquerySelectorsSettings} which are assigned to given application or a new default instance.
// *
// * This is an internal API method, please don't use it.
// *
// * @return assigned {@link IWicketJquerySelectorsSettings}
// */
// public static IWicketJquerySelectorsSettings assignedSettingsOrDefault() {
// Application app = Application.exists() ? Application.get() : null;
//
// if (isInstalled(app)) {
// return settings();
// } else {
// LOG.info("try to get settings, but WicketJquerySelectors wasn't installed to current application. Fallback to default settings.");
//
// return new WicketJquerySelectorsSettings();
// }
// }
//
// /**
// * returns the {@link IWicketJquerySelectorsSettings} which are assigned to current application
// *
// * @return assigned {@link IWicketJquerySelectorsSettings}
// */
// public static IWicketJquerySelectorsSettings settings() {
// if (Application.exists()) {
// final IWicketJquerySelectorsSettings settings = Application.get().getMetaData(JQUERY_SELECTORS_SETTINGS_METADATA_KEY);
//
// if (settings != null) {
// return settings;
// } else {
// throw new IllegalStateException("you have to call WicketJquerySelectors.install()");
// }
// }
//
// throw new IllegalStateException("there is no active application assigned to this thread.");
// }
//
// /**
// * private constructor.
// */
// private WicketJquerySelectors() {
// throw new UnsupportedOperationException();
// }
// }
//
// Path: src/main/java/de/agilecoders/wicket/jquery/settings/ObjectMapperFactory.java
// public interface ObjectMapperFactory {
//
// /**
// * @return new object mapper instance
// */
// ObjectMapper newObjectMapper();
// }
// Path: src/main/java/de/agilecoders/wicket/jquery/util/Json.java
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import de.agilecoders.wicket.jquery.WicketJquerySelectors;
import de.agilecoders.wicket.jquery.settings.ObjectMapperFactory;
import org.apache.wicket.util.io.IClusterable;
import org.apache.wicket.util.lang.Args;
import org.apache.wicket.util.string.Strings;
package de.agilecoders.wicket.jquery.util;
/**
* Helper functions to handle JsonNode values.
*
* @author miha
*/
public final class Json {
/**
* lazy holder to give application the chance to install its own
*/
private static final class Holder { | private static final ObjectMapperFactory factory = WicketJquerySelectors.assignedSettingsOrDefault().getObjectMapperFactory(); |
l0rdn1kk0n/wicket-jquery-selectors | src/main/java/de/agilecoders/wicket/jquery/util/Json.java | // Path: src/main/java/de/agilecoders/wicket/jquery/WicketJquerySelectors.java
// public final class WicketJquerySelectors {
// private static final Logger LOG = LoggerFactory.getLogger("wicket-jquery-selectors");
//
// /**
// * The {@link org.apache.wicket.MetaDataKey} used to retrieve the {@link de.agilecoders.wicket.jquery.settings.IWicketJquerySelectorsSettings}
// * from the Wicket {@link Appendable}.
// */
// private static final MetaDataKey<IWicketJquerySelectorsSettings> JQUERY_SELECTORS_SETTINGS_METADATA_KEY = new MetaDataKey<IWicketJquerySelectorsSettings>() {
// };
//
// /**
// * Checks whether this library support is already installed
// *
// * @param application the wicket application
// * @return {@code true} if library is already installed, otherwise {@code false}
// */
// public static boolean isInstalled(Application application) {
// return application != null && application.getMetaData(JQUERY_SELECTORS_SETTINGS_METADATA_KEY) != null;
// }
// /**
// * installs the library to given application
// *
// * @param app the wicket application
// */
// public static void install(final Application app) {
// install(app, null);
// }
//
// /**
// * installs the library settings to given app.
// *
// * @param app the wicket application
// * @param settings the settings to use
// */
// public static void install(Application app, IWicketJquerySelectorsSettings settings) {
// final IWicketJquerySelectorsSettings existingSettings = settings(app);
//
// if (existingSettings == null) {
// if (settings == null) {
// settings = new WicketJquerySelectorsSettings();
// }
//
// app.setMetaData(JQUERY_SELECTORS_SETTINGS_METADATA_KEY, settings);
//
// LOG.info("initialize wicket jquery selectors with given settings: {}", settings);
// }
// }
//
// /**
// * returns the {@link IWicketJquerySelectorsSettings} which are assigned to given application
// *
// * @param app The current application
// * @return assigned {@link IWicketJquerySelectorsSettings}
// */
// public static IWicketJquerySelectorsSettings settings(final Application app) {
// return app.getMetaData(JQUERY_SELECTORS_SETTINGS_METADATA_KEY);
// }
//
// /**
// * returns the {@link IWicketJquerySelectorsSettings} which are assigned to given application or a new default instance.
// *
// * This is an internal API method, please don't use it.
// *
// * @return assigned {@link IWicketJquerySelectorsSettings}
// */
// public static IWicketJquerySelectorsSettings assignedSettingsOrDefault() {
// Application app = Application.exists() ? Application.get() : null;
//
// if (isInstalled(app)) {
// return settings();
// } else {
// LOG.info("try to get settings, but WicketJquerySelectors wasn't installed to current application. Fallback to default settings.");
//
// return new WicketJquerySelectorsSettings();
// }
// }
//
// /**
// * returns the {@link IWicketJquerySelectorsSettings} which are assigned to current application
// *
// * @return assigned {@link IWicketJquerySelectorsSettings}
// */
// public static IWicketJquerySelectorsSettings settings() {
// if (Application.exists()) {
// final IWicketJquerySelectorsSettings settings = Application.get().getMetaData(JQUERY_SELECTORS_SETTINGS_METADATA_KEY);
//
// if (settings != null) {
// return settings;
// } else {
// throw new IllegalStateException("you have to call WicketJquerySelectors.install()");
// }
// }
//
// throw new IllegalStateException("there is no active application assigned to this thread.");
// }
//
// /**
// * private constructor.
// */
// private WicketJquerySelectors() {
// throw new UnsupportedOperationException();
// }
// }
//
// Path: src/main/java/de/agilecoders/wicket/jquery/settings/ObjectMapperFactory.java
// public interface ObjectMapperFactory {
//
// /**
// * @return new object mapper instance
// */
// ObjectMapper newObjectMapper();
// }
| import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import de.agilecoders.wicket.jquery.WicketJquerySelectors;
import de.agilecoders.wicket.jquery.settings.ObjectMapperFactory;
import org.apache.wicket.util.io.IClusterable;
import org.apache.wicket.util.lang.Args;
import org.apache.wicket.util.string.Strings; | package de.agilecoders.wicket.jquery.util;
/**
* Helper functions to handle JsonNode values.
*
* @author miha
*/
public final class Json {
/**
* lazy holder to give application the chance to install its own
*/
private static final class Holder { | // Path: src/main/java/de/agilecoders/wicket/jquery/WicketJquerySelectors.java
// public final class WicketJquerySelectors {
// private static final Logger LOG = LoggerFactory.getLogger("wicket-jquery-selectors");
//
// /**
// * The {@link org.apache.wicket.MetaDataKey} used to retrieve the {@link de.agilecoders.wicket.jquery.settings.IWicketJquerySelectorsSettings}
// * from the Wicket {@link Appendable}.
// */
// private static final MetaDataKey<IWicketJquerySelectorsSettings> JQUERY_SELECTORS_SETTINGS_METADATA_KEY = new MetaDataKey<IWicketJquerySelectorsSettings>() {
// };
//
// /**
// * Checks whether this library support is already installed
// *
// * @param application the wicket application
// * @return {@code true} if library is already installed, otherwise {@code false}
// */
// public static boolean isInstalled(Application application) {
// return application != null && application.getMetaData(JQUERY_SELECTORS_SETTINGS_METADATA_KEY) != null;
// }
// /**
// * installs the library to given application
// *
// * @param app the wicket application
// */
// public static void install(final Application app) {
// install(app, null);
// }
//
// /**
// * installs the library settings to given app.
// *
// * @param app the wicket application
// * @param settings the settings to use
// */
// public static void install(Application app, IWicketJquerySelectorsSettings settings) {
// final IWicketJquerySelectorsSettings existingSettings = settings(app);
//
// if (existingSettings == null) {
// if (settings == null) {
// settings = new WicketJquerySelectorsSettings();
// }
//
// app.setMetaData(JQUERY_SELECTORS_SETTINGS_METADATA_KEY, settings);
//
// LOG.info("initialize wicket jquery selectors with given settings: {}", settings);
// }
// }
//
// /**
// * returns the {@link IWicketJquerySelectorsSettings} which are assigned to given application
// *
// * @param app The current application
// * @return assigned {@link IWicketJquerySelectorsSettings}
// */
// public static IWicketJquerySelectorsSettings settings(final Application app) {
// return app.getMetaData(JQUERY_SELECTORS_SETTINGS_METADATA_KEY);
// }
//
// /**
// * returns the {@link IWicketJquerySelectorsSettings} which are assigned to given application or a new default instance.
// *
// * This is an internal API method, please don't use it.
// *
// * @return assigned {@link IWicketJquerySelectorsSettings}
// */
// public static IWicketJquerySelectorsSettings assignedSettingsOrDefault() {
// Application app = Application.exists() ? Application.get() : null;
//
// if (isInstalled(app)) {
// return settings();
// } else {
// LOG.info("try to get settings, but WicketJquerySelectors wasn't installed to current application. Fallback to default settings.");
//
// return new WicketJquerySelectorsSettings();
// }
// }
//
// /**
// * returns the {@link IWicketJquerySelectorsSettings} which are assigned to current application
// *
// * @return assigned {@link IWicketJquerySelectorsSettings}
// */
// public static IWicketJquerySelectorsSettings settings() {
// if (Application.exists()) {
// final IWicketJquerySelectorsSettings settings = Application.get().getMetaData(JQUERY_SELECTORS_SETTINGS_METADATA_KEY);
//
// if (settings != null) {
// return settings;
// } else {
// throw new IllegalStateException("you have to call WicketJquerySelectors.install()");
// }
// }
//
// throw new IllegalStateException("there is no active application assigned to this thread.");
// }
//
// /**
// * private constructor.
// */
// private WicketJquerySelectors() {
// throw new UnsupportedOperationException();
// }
// }
//
// Path: src/main/java/de/agilecoders/wicket/jquery/settings/ObjectMapperFactory.java
// public interface ObjectMapperFactory {
//
// /**
// * @return new object mapper instance
// */
// ObjectMapper newObjectMapper();
// }
// Path: src/main/java/de/agilecoders/wicket/jquery/util/Json.java
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import de.agilecoders.wicket.jquery.WicketJquerySelectors;
import de.agilecoders.wicket.jquery.settings.ObjectMapperFactory;
import org.apache.wicket.util.io.IClusterable;
import org.apache.wicket.util.lang.Args;
import org.apache.wicket.util.string.Strings;
package de.agilecoders.wicket.jquery.util;
/**
* Helper functions to handle JsonNode values.
*
* @author miha
*/
public final class Json {
/**
* lazy holder to give application the chance to install its own
*/
private static final class Holder { | private static final ObjectMapperFactory factory = WicketJquerySelectors.assignedSettingsOrDefault().getObjectMapperFactory(); |
l0rdn1kk0n/wicket-jquery-selectors | src/test/java/de/agilecoders/wicket/jquery/util/CharSequenceWrapperTest.java | // Path: src/test/java/de/agilecoders/wicket/jquery/SimpleConfig.java
// public class SimpleConfig extends AbstractConfig {
// private static final IKey<String> string = newKey("string", null);
// private static final IKey<Integer> integer = newKey("integer", null);
//
// public SimpleConfig() {
// put(string, "1");
// put(integer, 1);
// }
// }
| import de.agilecoders.wicket.jquery.SimpleConfig;
import org.junit.Assert;
import org.junit.Test;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is; | package de.agilecoders.wicket.jquery.util;
/**
* Test for CharSequenceWrapper
*/
public class CharSequenceWrapperTest extends Assert {
@Test
public void config() { | // Path: src/test/java/de/agilecoders/wicket/jquery/SimpleConfig.java
// public class SimpleConfig extends AbstractConfig {
// private static final IKey<String> string = newKey("string", null);
// private static final IKey<Integer> integer = newKey("integer", null);
//
// public SimpleConfig() {
// put(string, "1");
// put(integer, 1);
// }
// }
// Path: src/test/java/de/agilecoders/wicket/jquery/util/CharSequenceWrapperTest.java
import de.agilecoders.wicket.jquery.SimpleConfig;
import org.junit.Assert;
import org.junit.Test;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
package de.agilecoders.wicket.jquery.util;
/**
* Test for CharSequenceWrapper
*/
public class CharSequenceWrapperTest extends Assert {
@Test
public void config() { | CharSequence cs = new CharSequenceWrapper(new SimpleConfig()); |
impiaaa/MyWorldGen | src/main/java/net/boatcake/MyWorldGen/blocks/BlockPlacementMaterialAnchor.java | // Path: src/main/java/net/boatcake/MyWorldGen/blocks/BlockAnchorMaterial.java
// public enum AnchorType implements IStringSerializable {
// GROUND(0, "ground", null), AIR(1, "air", null), STONE(2, "stone", Material.rock), WATER(3, "water",
// Material.water), LAVA(4, "lava", Material.lava), DIRT(5, "dirt", Material.ground), WOOD(6, "wood",
// Material.wood), LEAVES(7, "leaves", Material.leaves), SAND(8, "sand", Material.sand);
//
// public static AnchorType get(int id) {
// for (AnchorType a : AnchorType.values()) {
// if (a.id == id) {
// return a;
// }
// }
// return null;
// }
//
// public final int id;
// public final Material material;
// public final String name;
//
// private AnchorType(int id, String name, Material mat) {
// this.id = id;
// this.name = name;
// this.material = mat;
// }
//
// @Override
// public String getName() {
// return name;
// }
// }
| import net.boatcake.MyWorldGen.blocks.BlockAnchorMaterial.AnchorType;
import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Blocks;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraft.world.biome.BiomeGenBase; | package net.boatcake.MyWorldGen.blocks;
public class BlockPlacementMaterialAnchor extends BlockPlacementLogic {
public BlockPlacementMaterialAnchor(String blockName) {
super(blockName);
}
@Override
public void affectWorld(int myMeta, TileEntity myTileEntity, World world, BlockPos pos, boolean matchTerrain) {
if (matchTerrain) { | // Path: src/main/java/net/boatcake/MyWorldGen/blocks/BlockAnchorMaterial.java
// public enum AnchorType implements IStringSerializable {
// GROUND(0, "ground", null), AIR(1, "air", null), STONE(2, "stone", Material.rock), WATER(3, "water",
// Material.water), LAVA(4, "lava", Material.lava), DIRT(5, "dirt", Material.ground), WOOD(6, "wood",
// Material.wood), LEAVES(7, "leaves", Material.leaves), SAND(8, "sand", Material.sand);
//
// public static AnchorType get(int id) {
// for (AnchorType a : AnchorType.values()) {
// if (a.id == id) {
// return a;
// }
// }
// return null;
// }
//
// public final int id;
// public final Material material;
// public final String name;
//
// private AnchorType(int id, String name, Material mat) {
// this.id = id;
// this.name = name;
// this.material = mat;
// }
//
// @Override
// public String getName() {
// return name;
// }
// }
// Path: src/main/java/net/boatcake/MyWorldGen/blocks/BlockPlacementMaterialAnchor.java
import net.boatcake.MyWorldGen.blocks.BlockAnchorMaterial.AnchorType;
import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Blocks;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraft.world.biome.BiomeGenBase;
package net.boatcake.MyWorldGen.blocks;
public class BlockPlacementMaterialAnchor extends BlockPlacementLogic {
public BlockPlacementMaterialAnchor(String blockName) {
super(blockName);
}
@Override
public void affectWorld(int myMeta, TileEntity myTileEntity, World world, BlockPos pos, boolean matchTerrain) {
if (matchTerrain) { | switch (AnchorType.get(myMeta)) { |
impiaaa/MyWorldGen | src/main/java/net/boatcake/MyWorldGen/WorldGenerator.java | // Path: src/main/java/net/boatcake/MyWorldGen/utils/SchematicFilenameFilter.java
// public class SchematicFilenameFilter implements FilenameFilter {
// @Override
// public boolean accept(File dir, String name) {
// return name.toLowerCase().endsWith(".schematic");
// }
// }
| import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Random;
import org.apache.logging.log4j.Level;
import net.boatcake.MyWorldGen.utils.SchematicFilenameFilter;
import net.minecraft.nbt.CompressedStreamTools;
import net.minecraft.util.Rotation;
import net.minecraft.util.WeightedRandom;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.chunk.IChunkGenerator;
import net.minecraft.world.chunk.IChunkProvider;
import net.minecraftforge.fml.common.IWorldGenerator; | package net.boatcake.MyWorldGen;
public class WorldGenerator implements IWorldGenerator {
private List<Schematic> worldgenFolderSchemList;
public List<Schematic> resourcePackSchemList;
// Dumb lock to prevent stack overflow when structures cause chunks to
// generate
// TODO: Ideally, structures should not ever cause chunks to generate,
// instead waiting until all required chunks are loaded to check for a
// valid location. However, that's non-trivial, and would probably require
// a chunk load handler (though I'd need that for retro-gen anyway)
private int currentlyGenerating;
private static int GENERATING_STACK_LIMIT = 5;
public WorldGenerator() {
worldgenFolderSchemList = new ArrayList<Schematic>();
resourcePackSchemList = new ArrayList<Schematic>();
currentlyGenerating = 0;
}
public void addSchematicsFromDirectory(File schemDirectory) { | // Path: src/main/java/net/boatcake/MyWorldGen/utils/SchematicFilenameFilter.java
// public class SchematicFilenameFilter implements FilenameFilter {
// @Override
// public boolean accept(File dir, String name) {
// return name.toLowerCase().endsWith(".schematic");
// }
// }
// Path: src/main/java/net/boatcake/MyWorldGen/WorldGenerator.java
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Random;
import org.apache.logging.log4j.Level;
import net.boatcake.MyWorldGen.utils.SchematicFilenameFilter;
import net.minecraft.nbt.CompressedStreamTools;
import net.minecraft.util.Rotation;
import net.minecraft.util.WeightedRandom;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.chunk.IChunkGenerator;
import net.minecraft.world.chunk.IChunkProvider;
import net.minecraftforge.fml.common.IWorldGenerator;
package net.boatcake.MyWorldGen;
public class WorldGenerator implements IWorldGenerator {
private List<Schematic> worldgenFolderSchemList;
public List<Schematic> resourcePackSchemList;
// Dumb lock to prevent stack overflow when structures cause chunks to
// generate
// TODO: Ideally, structures should not ever cause chunks to generate,
// instead waiting until all required chunks are loaded to check for a
// valid location. However, that's non-trivial, and would probably require
// a chunk load handler (though I'd need that for retro-gen anyway)
private int currentlyGenerating;
private static int GENERATING_STACK_LIMIT = 5;
public WorldGenerator() {
worldgenFolderSchemList = new ArrayList<Schematic>();
resourcePackSchemList = new ArrayList<Schematic>();
currentlyGenerating = 0;
}
public void addSchematicsFromDirectory(File schemDirectory) { | File[] schemFiles = schemDirectory.listFiles(new SchematicFilenameFilter()); |
impiaaa/MyWorldGen | src/main/java/net/boatcake/MyWorldGen/items/BlockAnchorItem.java | // Path: src/main/java/net/boatcake/MyWorldGen/blocks/BlockAnchorMaterial.java
// public class BlockAnchorMaterial extends Block implements BlockAnchorBase {
// public enum AnchorType implements IStringSerializable {
// GROUND(0, "ground", null), AIR(1, "air", null), STONE(2, "stone", Material.rock), WATER(3, "water",
// Material.water), LAVA(4, "lava", Material.lava), DIRT(5, "dirt", Material.ground), WOOD(6, "wood",
// Material.wood), LEAVES(7, "leaves", Material.leaves), SAND(8, "sand", Material.sand);
//
// public static AnchorType get(int id) {
// for (AnchorType a : AnchorType.values()) {
// if (a.id == id) {
// return a;
// }
// }
// return null;
// }
//
// public final int id;
// public final Material material;
// public final String name;
//
// private AnchorType(int id, String name, Material mat) {
// this.id = id;
// this.name = name;
// this.material = mat;
// }
//
// @Override
// public String getName() {
// return name;
// }
// }
//
// public static final PropertyEnum<AnchorType> TYPE_PROP = PropertyEnum.create("type", AnchorType.class);
//
// public BlockAnchorMaterial(Material par2Material) {
// super(par2Material);
// setBlockUnbreakable();
// setResistance(6000000.0F);
// setDefaultState(blockState.getBaseState().withProperty(TYPE_PROP, AnchorType.GROUND));
// }
//
// @Override
// public int damageDropped(IBlockState state) {
// return state.getValue(TYPE_PROP).id;
// }
//
// @Override
// @SideOnly(Side.CLIENT)
// public void getSubBlocks(Item item, CreativeTabs creativeTabs, List<ItemStack> subBlockList) {
// for (AnchorType a : AnchorType.values()) {
// subBlockList.add(new ItemStack(item, 1, a.id));
// }
// }
//
// @Override
// public IBlockState getStateFromMeta(int meta) {
// return getDefaultState().withProperty(TYPE_PROP, AnchorType.get(meta));
// }
//
// @Override
// public int getMetaFromState(IBlockState state) {
// return state.getValue(TYPE_PROP).id;
// }
//
// @Override
// protected BlockStateContainer createBlockState() {
// return new BlockStateContainer(this, new IProperty[] { TYPE_PROP });
// }
// }
| import com.google.common.base.Function;
import net.boatcake.MyWorldGen.blocks.BlockAnchorMaterial;
import net.minecraft.block.Block;
import net.minecraft.item.ItemMultiTexture;
import net.minecraft.item.ItemStack; | package net.boatcake.MyWorldGen.items;
public class BlockAnchorItem extends ItemMultiTexture {
public BlockAnchorItem(Block block) {
super(block, block, new Function<ItemStack, String>() {
@Override
public String apply(ItemStack stack) { | // Path: src/main/java/net/boatcake/MyWorldGen/blocks/BlockAnchorMaterial.java
// public class BlockAnchorMaterial extends Block implements BlockAnchorBase {
// public enum AnchorType implements IStringSerializable {
// GROUND(0, "ground", null), AIR(1, "air", null), STONE(2, "stone", Material.rock), WATER(3, "water",
// Material.water), LAVA(4, "lava", Material.lava), DIRT(5, "dirt", Material.ground), WOOD(6, "wood",
// Material.wood), LEAVES(7, "leaves", Material.leaves), SAND(8, "sand", Material.sand);
//
// public static AnchorType get(int id) {
// for (AnchorType a : AnchorType.values()) {
// if (a.id == id) {
// return a;
// }
// }
// return null;
// }
//
// public final int id;
// public final Material material;
// public final String name;
//
// private AnchorType(int id, String name, Material mat) {
// this.id = id;
// this.name = name;
// this.material = mat;
// }
//
// @Override
// public String getName() {
// return name;
// }
// }
//
// public static final PropertyEnum<AnchorType> TYPE_PROP = PropertyEnum.create("type", AnchorType.class);
//
// public BlockAnchorMaterial(Material par2Material) {
// super(par2Material);
// setBlockUnbreakable();
// setResistance(6000000.0F);
// setDefaultState(blockState.getBaseState().withProperty(TYPE_PROP, AnchorType.GROUND));
// }
//
// @Override
// public int damageDropped(IBlockState state) {
// return state.getValue(TYPE_PROP).id;
// }
//
// @Override
// @SideOnly(Side.CLIENT)
// public void getSubBlocks(Item item, CreativeTabs creativeTabs, List<ItemStack> subBlockList) {
// for (AnchorType a : AnchorType.values()) {
// subBlockList.add(new ItemStack(item, 1, a.id));
// }
// }
//
// @Override
// public IBlockState getStateFromMeta(int meta) {
// return getDefaultState().withProperty(TYPE_PROP, AnchorType.get(meta));
// }
//
// @Override
// public int getMetaFromState(IBlockState state) {
// return state.getValue(TYPE_PROP).id;
// }
//
// @Override
// protected BlockStateContainer createBlockState() {
// return new BlockStateContainer(this, new IProperty[] { TYPE_PROP });
// }
// }
// Path: src/main/java/net/boatcake/MyWorldGen/items/BlockAnchorItem.java
import com.google.common.base.Function;
import net.boatcake.MyWorldGen.blocks.BlockAnchorMaterial;
import net.minecraft.block.Block;
import net.minecraft.item.ItemMultiTexture;
import net.minecraft.item.ItemStack;
package net.boatcake.MyWorldGen.items;
public class BlockAnchorItem extends ItemMultiTexture {
public BlockAnchorItem(Block block) {
super(block, block, new Function<ItemStack, String>() {
@Override
public String apply(ItemStack stack) { | return BlockAnchorMaterial.AnchorType.get(stack.getMetadata()).name; |
stephenh/mirror | src/main/java/mirror/SaveToLocal.java | // Path: src/main/java/mirror/Utils.java
// public static String abbreviatePath(String path) {
// if (StringUtils.countMatches(path, '/') < 2) {
// return path;
// } else {
// return StringUtils.substringBefore(path, "/") + "/.../" + StringUtils.substringAfterLast(path, "/");
// }
// }
//
// Path: src/main/java/mirror/Utils.java
// public static String debugString(Update u) {
// return "[" + TextFormat.shortDebugString(u).replace(": ", ":") + "]";
// }
//
// Path: src/main/java/mirror/tasks/TaskLogic.java
// public interface TaskLogic {
//
// /** Run one interaction, and return how long the task wants to sleep. */
// Duration runOneLoop() throws InterruptedException;
//
// /** Called on the task thread, before we start calling {@link #runOneLoop()} in a loop. */
// default void onStart() throws InterruptedException {
// }
//
// default void onFailure() throws InterruptedException {
// }
//
// /** Called on the task thread, after we've interrupted/stopped calling {@link #runOneLoop()}. */
// default void onStop() throws InterruptedException {
// }
//
// /**
// * Called off the task thread, when we're trying to interrupt the task.
// *
// * Most threads shouldn't need this because they'll shut down
// * when we call thread.interrupt().
// */
// default void onInterrupt() {
// }
//
// default String getName() {
// String name = getClass().getSimpleName();
// // lambdas don't have simple names
// if (name.equals("")) {
// name = StringUtils.substringAfterLast(getClass().getName(), ".");
// }
// return name;
// }
// }
| import static mirror.Utils.abbreviatePath;
import static mirror.Utils.debugString;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.util.concurrent.BlockingQueue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.annotations.VisibleForTesting;
import mirror.tasks.TaskLogic; | @Override
public Duration runOneLoop() throws InterruptedException {
Update u = results.take();
try {
saveLocally(u);
} catch (RuntimeException e) {
log.error("Exception with results " + u, e);
}
return null;
}
@VisibleForTesting
void drain() throws Exception {
while (!results.isEmpty()) {
saveLocally(results.take());
}
}
private void saveLocally(Update remote) {
try {
if (remote.getDelete()) {
deleteLocally(remote);
} else if (!remote.getSymlink().isEmpty()) {
saveSymlinkLocally(remote);
} else if (remote.getDirectory()) {
createDirectoryLocally(remote);
} else {
saveFileLocally(remote);
}
} catch (IOException e) { | // Path: src/main/java/mirror/Utils.java
// public static String abbreviatePath(String path) {
// if (StringUtils.countMatches(path, '/') < 2) {
// return path;
// } else {
// return StringUtils.substringBefore(path, "/") + "/.../" + StringUtils.substringAfterLast(path, "/");
// }
// }
//
// Path: src/main/java/mirror/Utils.java
// public static String debugString(Update u) {
// return "[" + TextFormat.shortDebugString(u).replace(": ", ":") + "]";
// }
//
// Path: src/main/java/mirror/tasks/TaskLogic.java
// public interface TaskLogic {
//
// /** Run one interaction, and return how long the task wants to sleep. */
// Duration runOneLoop() throws InterruptedException;
//
// /** Called on the task thread, before we start calling {@link #runOneLoop()} in a loop. */
// default void onStart() throws InterruptedException {
// }
//
// default void onFailure() throws InterruptedException {
// }
//
// /** Called on the task thread, after we've interrupted/stopped calling {@link #runOneLoop()}. */
// default void onStop() throws InterruptedException {
// }
//
// /**
// * Called off the task thread, when we're trying to interrupt the task.
// *
// * Most threads shouldn't need this because they'll shut down
// * when we call thread.interrupt().
// */
// default void onInterrupt() {
// }
//
// default String getName() {
// String name = getClass().getSimpleName();
// // lambdas don't have simple names
// if (name.equals("")) {
// name = StringUtils.substringAfterLast(getClass().getName(), ".");
// }
// return name;
// }
// }
// Path: src/main/java/mirror/SaveToLocal.java
import static mirror.Utils.abbreviatePath;
import static mirror.Utils.debugString;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.util.concurrent.BlockingQueue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.annotations.VisibleForTesting;
import mirror.tasks.TaskLogic;
@Override
public Duration runOneLoop() throws InterruptedException {
Update u = results.take();
try {
saveLocally(u);
} catch (RuntimeException e) {
log.error("Exception with results " + u, e);
}
return null;
}
@VisibleForTesting
void drain() throws Exception {
while (!results.isEmpty()) {
saveLocally(results.take());
}
}
private void saveLocally(Update remote) {
try {
if (remote.getDelete()) {
deleteLocally(remote);
} else if (!remote.getSymlink().isEmpty()) {
saveSymlinkLocally(remote);
} else if (remote.getDirectory()) {
createDirectoryLocally(remote);
} else {
saveFileLocally(remote);
}
} catch (IOException e) { | log.error("Error saving " + debugString(remote), e); |
stephenh/mirror | src/main/java/mirror/SaveToLocal.java | // Path: src/main/java/mirror/Utils.java
// public static String abbreviatePath(String path) {
// if (StringUtils.countMatches(path, '/') < 2) {
// return path;
// } else {
// return StringUtils.substringBefore(path, "/") + "/.../" + StringUtils.substringAfterLast(path, "/");
// }
// }
//
// Path: src/main/java/mirror/Utils.java
// public static String debugString(Update u) {
// return "[" + TextFormat.shortDebugString(u).replace(": ", ":") + "]";
// }
//
// Path: src/main/java/mirror/tasks/TaskLogic.java
// public interface TaskLogic {
//
// /** Run one interaction, and return how long the task wants to sleep. */
// Duration runOneLoop() throws InterruptedException;
//
// /** Called on the task thread, before we start calling {@link #runOneLoop()} in a loop. */
// default void onStart() throws InterruptedException {
// }
//
// default void onFailure() throws InterruptedException {
// }
//
// /** Called on the task thread, after we've interrupted/stopped calling {@link #runOneLoop()}. */
// default void onStop() throws InterruptedException {
// }
//
// /**
// * Called off the task thread, when we're trying to interrupt the task.
// *
// * Most threads shouldn't need this because they'll shut down
// * when we call thread.interrupt().
// */
// default void onInterrupt() {
// }
//
// default String getName() {
// String name = getClass().getSimpleName();
// // lambdas don't have simple names
// if (name.equals("")) {
// name = StringUtils.substringAfterLast(getClass().getName(), ".");
// }
// return name;
// }
// }
| import static mirror.Utils.abbreviatePath;
import static mirror.Utils.debugString;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.util.concurrent.BlockingQueue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.annotations.VisibleForTesting;
import mirror.tasks.TaskLogic; | }
@VisibleForTesting
void drain() throws Exception {
while (!results.isEmpty()) {
saveLocally(results.take());
}
}
private void saveLocally(Update remote) {
try {
if (remote.getDelete()) {
deleteLocally(remote);
} else if (!remote.getSymlink().isEmpty()) {
saveSymlinkLocally(remote);
} else if (remote.getDirectory()) {
createDirectoryLocally(remote);
} else {
saveFileLocally(remote);
}
} catch (IOException e) {
log.error("Error saving " + debugString(remote), e);
}
}
// Note that this will generate a new local delete event (because we should
// only be doing this when we want to immediately re-create the path as a
// different type, e.g. a file -> a directory), but we end up ignoring
// this stale delete event with isStaleLocalUpdate
private void deleteLocally(Update remote) throws IOException { | // Path: src/main/java/mirror/Utils.java
// public static String abbreviatePath(String path) {
// if (StringUtils.countMatches(path, '/') < 2) {
// return path;
// } else {
// return StringUtils.substringBefore(path, "/") + "/.../" + StringUtils.substringAfterLast(path, "/");
// }
// }
//
// Path: src/main/java/mirror/Utils.java
// public static String debugString(Update u) {
// return "[" + TextFormat.shortDebugString(u).replace(": ", ":") + "]";
// }
//
// Path: src/main/java/mirror/tasks/TaskLogic.java
// public interface TaskLogic {
//
// /** Run one interaction, and return how long the task wants to sleep. */
// Duration runOneLoop() throws InterruptedException;
//
// /** Called on the task thread, before we start calling {@link #runOneLoop()} in a loop. */
// default void onStart() throws InterruptedException {
// }
//
// default void onFailure() throws InterruptedException {
// }
//
// /** Called on the task thread, after we've interrupted/stopped calling {@link #runOneLoop()}. */
// default void onStop() throws InterruptedException {
// }
//
// /**
// * Called off the task thread, when we're trying to interrupt the task.
// *
// * Most threads shouldn't need this because they'll shut down
// * when we call thread.interrupt().
// */
// default void onInterrupt() {
// }
//
// default String getName() {
// String name = getClass().getSimpleName();
// // lambdas don't have simple names
// if (name.equals("")) {
// name = StringUtils.substringAfterLast(getClass().getName(), ".");
// }
// return name;
// }
// }
// Path: src/main/java/mirror/SaveToLocal.java
import static mirror.Utils.abbreviatePath;
import static mirror.Utils.debugString;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.util.concurrent.BlockingQueue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.annotations.VisibleForTesting;
import mirror.tasks.TaskLogic;
}
@VisibleForTesting
void drain() throws Exception {
while (!results.isEmpty()) {
saveLocally(results.take());
}
}
private void saveLocally(Update remote) {
try {
if (remote.getDelete()) {
deleteLocally(remote);
} else if (!remote.getSymlink().isEmpty()) {
saveSymlinkLocally(remote);
} else if (remote.getDirectory()) {
createDirectoryLocally(remote);
} else {
saveFileLocally(remote);
}
} catch (IOException e) {
log.error("Error saving " + debugString(remote), e);
}
}
// Note that this will generate a new local delete event (because we should
// only be doing this when we want to immediately re-create the path as a
// different type, e.g. a file -> a directory), but we end up ignoring
// this stale delete event with isStaleLocalUpdate
private void deleteLocally(Update remote) throws IOException { | log.info("Remote delete {}", abbreviatePath(remote.getPath())); |
stephenh/mirror | src/main/java/mirror/SyncLogic.java | // Path: src/main/java/mirror/UpdateTreeDiff.java
// public static class DiffResults {
// public final List<Update> sendToRemote = new ArrayList<>();
// public final List<Update> saveLocally = new ArrayList<>();
//
// @Override
// public String toString() {
// return "[sendToRemote=" + sendToRemote.size() + ",saveLocally=" + saveLocally.size() + "]";
// }
// }
//
// Path: src/main/java/mirror/tasks/TaskLogic.java
// public interface TaskLogic {
//
// /** Run one interaction, and return how long the task wants to sleep. */
// Duration runOneLoop() throws InterruptedException;
//
// /** Called on the task thread, before we start calling {@link #runOneLoop()} in a loop. */
// default void onStart() throws InterruptedException {
// }
//
// default void onFailure() throws InterruptedException {
// }
//
// /** Called on the task thread, after we've interrupted/stopped calling {@link #runOneLoop()}. */
// default void onStop() throws InterruptedException {
// }
//
// /**
// * Called off the task thread, when we're trying to interrupt the task.
// *
// * Most threads shouldn't need this because they'll shut down
// * when we call thread.interrupt().
// */
// default void onInterrupt() {
// }
//
// default String getName() {
// String name = getClass().getSimpleName();
// // lambdas don't have simple names
// if (name.equals("")) {
// name = StringUtils.substringAfterLast(getClass().getName(), ".");
// }
// return name;
// }
// }
| import static org.apache.commons.lang3.StringUtils.defaultIfEmpty;
import static org.apache.commons.lang3.StringUtils.substringAfterLast;
import static org.jooq.lambda.Seq.seq;
import static org.jooq.lambda.tuple.Tuple.tuple;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.jooq.lambda.tuple.Tuple2;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.annotations.VisibleForTesting;
import mirror.UpdateTreeDiff.DiffResults;
import mirror.tasks.TaskLogic; | private List<Update> getNextBatchOrBlock() throws InterruptedException {
List<Update> updates = new ArrayList<>();
// block for at least one
updates.add(queues.incomingQueue.take());
// now go ahead and drain the rest while we're here
queues.incomingQueue.drainTo(updates);
return updates;
}
@VisibleForTesting
void poll() throws IOException, InterruptedException {
Update u;
while ((u = queues.incomingQueue.poll()) != null) {
handleUpdate(u);
}
diff();
}
private void handleUpdate(Update u) throws InterruptedException {
if (u.getLocal()) {
if (isStaleLocalUpdate(u)) {
return;
}
tree.addLocal(ensureSettledAndReadModTime(u));
} else {
tree.addRemote(u);
}
}
private void diff() throws InterruptedException { | // Path: src/main/java/mirror/UpdateTreeDiff.java
// public static class DiffResults {
// public final List<Update> sendToRemote = new ArrayList<>();
// public final List<Update> saveLocally = new ArrayList<>();
//
// @Override
// public String toString() {
// return "[sendToRemote=" + sendToRemote.size() + ",saveLocally=" + saveLocally.size() + "]";
// }
// }
//
// Path: src/main/java/mirror/tasks/TaskLogic.java
// public interface TaskLogic {
//
// /** Run one interaction, and return how long the task wants to sleep. */
// Duration runOneLoop() throws InterruptedException;
//
// /** Called on the task thread, before we start calling {@link #runOneLoop()} in a loop. */
// default void onStart() throws InterruptedException {
// }
//
// default void onFailure() throws InterruptedException {
// }
//
// /** Called on the task thread, after we've interrupted/stopped calling {@link #runOneLoop()}. */
// default void onStop() throws InterruptedException {
// }
//
// /**
// * Called off the task thread, when we're trying to interrupt the task.
// *
// * Most threads shouldn't need this because they'll shut down
// * when we call thread.interrupt().
// */
// default void onInterrupt() {
// }
//
// default String getName() {
// String name = getClass().getSimpleName();
// // lambdas don't have simple names
// if (name.equals("")) {
// name = StringUtils.substringAfterLast(getClass().getName(), ".");
// }
// return name;
// }
// }
// Path: src/main/java/mirror/SyncLogic.java
import static org.apache.commons.lang3.StringUtils.defaultIfEmpty;
import static org.apache.commons.lang3.StringUtils.substringAfterLast;
import static org.jooq.lambda.Seq.seq;
import static org.jooq.lambda.tuple.Tuple.tuple;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.jooq.lambda.tuple.Tuple2;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.annotations.VisibleForTesting;
import mirror.UpdateTreeDiff.DiffResults;
import mirror.tasks.TaskLogic;
private List<Update> getNextBatchOrBlock() throws InterruptedException {
List<Update> updates = new ArrayList<>();
// block for at least one
updates.add(queues.incomingQueue.take());
// now go ahead and drain the rest while we're here
queues.incomingQueue.drainTo(updates);
return updates;
}
@VisibleForTesting
void poll() throws IOException, InterruptedException {
Update u;
while ((u = queues.incomingQueue.poll()) != null) {
handleUpdate(u);
}
diff();
}
private void handleUpdate(Update u) throws InterruptedException {
if (u.getLocal()) {
if (isStaleLocalUpdate(u)) {
return;
}
tree.addLocal(ensureSettledAndReadModTime(u));
} else {
tree.addRemote(u);
}
}
private void diff() throws InterruptedException { | DiffResults r = new UpdateTreeDiff(tree).diff(); |
stephenh/mirror | src/main/java/mirror/MirrorClient.java | // Path: src/main/java/mirror/Utils.java
// public static MirrorStub withTimeout(MirrorStub s) {
// // over VPN, ~100k files can take 30 seconds.
// return s.withDeadlineAfter(10, TimeUnit.MINUTES);
// }
//
// Path: src/main/java/mirror/tasks/TaskFactory.java
// public interface TaskFactory {
//
// default TaskHandle runTask(TaskLogic logic) {
// return runTask(logic, null);
// }
//
// TaskHandle runTask(TaskLogic logic, Runnable onFailure);
//
// void stopTask(TaskLogic logic);
//
// default TaskPool newTaskPool() {
// return new TaskPool(this);
// }
//
// }
//
// Path: src/main/java/mirror/tasks/TaskLogic.java
// public interface TaskLogic {
//
// /** Run one interaction, and return how long the task wants to sleep. */
// Duration runOneLoop() throws InterruptedException;
//
// /** Called on the task thread, before we start calling {@link #runOneLoop()} in a loop. */
// default void onStart() throws InterruptedException {
// }
//
// default void onFailure() throws InterruptedException {
// }
//
// /** Called on the task thread, after we've interrupted/stopped calling {@link #runOneLoop()}. */
// default void onStop() throws InterruptedException {
// }
//
// /**
// * Called off the task thread, when we're trying to interrupt the task.
// *
// * Most threads shouldn't need this because they'll shut down
// * when we call thread.interrupt().
// */
// default void onInterrupt() {
// }
//
// default String getName() {
// String name = getClass().getSimpleName();
// // lambdas don't have simple names
// if (name.equals("")) {
// name = StringUtils.substringAfterLast(getClass().getName(), ".");
// }
// return name;
// }
// }
| import static mirror.Utils.withTimeout;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.time.Duration;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.util.concurrent.SettableFuture;
import io.grpc.ManagedChannel;
import io.grpc.stub.ClientCallStreamObserver;
import io.grpc.stub.ClientResponseObserver;
import io.grpc.stub.StreamObserver;
import mirror.MirrorGrpc.MirrorStub;
import mirror.tasks.TaskFactory;
import mirror.tasks.TaskLogic; | package mirror;
public class MirrorClient {
private static final Logger log = LoggerFactory.getLogger(MirrorClient.class);
private final MirrorPaths paths; | // Path: src/main/java/mirror/Utils.java
// public static MirrorStub withTimeout(MirrorStub s) {
// // over VPN, ~100k files can take 30 seconds.
// return s.withDeadlineAfter(10, TimeUnit.MINUTES);
// }
//
// Path: src/main/java/mirror/tasks/TaskFactory.java
// public interface TaskFactory {
//
// default TaskHandle runTask(TaskLogic logic) {
// return runTask(logic, null);
// }
//
// TaskHandle runTask(TaskLogic logic, Runnable onFailure);
//
// void stopTask(TaskLogic logic);
//
// default TaskPool newTaskPool() {
// return new TaskPool(this);
// }
//
// }
//
// Path: src/main/java/mirror/tasks/TaskLogic.java
// public interface TaskLogic {
//
// /** Run one interaction, and return how long the task wants to sleep. */
// Duration runOneLoop() throws InterruptedException;
//
// /** Called on the task thread, before we start calling {@link #runOneLoop()} in a loop. */
// default void onStart() throws InterruptedException {
// }
//
// default void onFailure() throws InterruptedException {
// }
//
// /** Called on the task thread, after we've interrupted/stopped calling {@link #runOneLoop()}. */
// default void onStop() throws InterruptedException {
// }
//
// /**
// * Called off the task thread, when we're trying to interrupt the task.
// *
// * Most threads shouldn't need this because they'll shut down
// * when we call thread.interrupt().
// */
// default void onInterrupt() {
// }
//
// default String getName() {
// String name = getClass().getSimpleName();
// // lambdas don't have simple names
// if (name.equals("")) {
// name = StringUtils.substringAfterLast(getClass().getName(), ".");
// }
// return name;
// }
// }
// Path: src/main/java/mirror/MirrorClient.java
import static mirror.Utils.withTimeout;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.time.Duration;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.util.concurrent.SettableFuture;
import io.grpc.ManagedChannel;
import io.grpc.stub.ClientCallStreamObserver;
import io.grpc.stub.ClientResponseObserver;
import io.grpc.stub.StreamObserver;
import mirror.MirrorGrpc.MirrorStub;
import mirror.tasks.TaskFactory;
import mirror.tasks.TaskLogic;
package mirror;
public class MirrorClient {
private static final Logger log = LoggerFactory.getLogger(MirrorClient.class);
private final MirrorPaths paths; | private final TaskFactory taskFactory; |
stephenh/mirror | src/main/java/mirror/MirrorClient.java | // Path: src/main/java/mirror/Utils.java
// public static MirrorStub withTimeout(MirrorStub s) {
// // over VPN, ~100k files can take 30 seconds.
// return s.withDeadlineAfter(10, TimeUnit.MINUTES);
// }
//
// Path: src/main/java/mirror/tasks/TaskFactory.java
// public interface TaskFactory {
//
// default TaskHandle runTask(TaskLogic logic) {
// return runTask(logic, null);
// }
//
// TaskHandle runTask(TaskLogic logic, Runnable onFailure);
//
// void stopTask(TaskLogic logic);
//
// default TaskPool newTaskPool() {
// return new TaskPool(this);
// }
//
// }
//
// Path: src/main/java/mirror/tasks/TaskLogic.java
// public interface TaskLogic {
//
// /** Run one interaction, and return how long the task wants to sleep. */
// Duration runOneLoop() throws InterruptedException;
//
// /** Called on the task thread, before we start calling {@link #runOneLoop()} in a loop. */
// default void onStart() throws InterruptedException {
// }
//
// default void onFailure() throws InterruptedException {
// }
//
// /** Called on the task thread, after we've interrupted/stopped calling {@link #runOneLoop()}. */
// default void onStop() throws InterruptedException {
// }
//
// /**
// * Called off the task thread, when we're trying to interrupt the task.
// *
// * Most threads shouldn't need this because they'll shut down
// * when we call thread.interrupt().
// */
// default void onInterrupt() {
// }
//
// default String getName() {
// String name = getClass().getSimpleName();
// // lambdas don't have simple names
// if (name.equals("")) {
// name = StringUtils.substringAfterLast(getClass().getName(), ".");
// }
// return name;
// }
// }
| import static mirror.Utils.withTimeout;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.time.Duration;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.util.concurrent.SettableFuture;
import io.grpc.ManagedChannel;
import io.grpc.stub.ClientCallStreamObserver;
import io.grpc.stub.ClientResponseObserver;
import io.grpc.stub.StreamObserver;
import mirror.MirrorGrpc.MirrorStub;
import mirror.tasks.TaskFactory;
import mirror.tasks.TaskLogic; | package mirror;
public class MirrorClient {
private static final Logger log = LoggerFactory.getLogger(MirrorClient.class);
private final MirrorPaths paths;
private final TaskFactory taskFactory;
private final ConnectionDetector detector;
private final FileWatcherFactory watcherFactory;
private final FileAccess fileAccess;
private final ChannelFactory channelFactory; | // Path: src/main/java/mirror/Utils.java
// public static MirrorStub withTimeout(MirrorStub s) {
// // over VPN, ~100k files can take 30 seconds.
// return s.withDeadlineAfter(10, TimeUnit.MINUTES);
// }
//
// Path: src/main/java/mirror/tasks/TaskFactory.java
// public interface TaskFactory {
//
// default TaskHandle runTask(TaskLogic logic) {
// return runTask(logic, null);
// }
//
// TaskHandle runTask(TaskLogic logic, Runnable onFailure);
//
// void stopTask(TaskLogic logic);
//
// default TaskPool newTaskPool() {
// return new TaskPool(this);
// }
//
// }
//
// Path: src/main/java/mirror/tasks/TaskLogic.java
// public interface TaskLogic {
//
// /** Run one interaction, and return how long the task wants to sleep. */
// Duration runOneLoop() throws InterruptedException;
//
// /** Called on the task thread, before we start calling {@link #runOneLoop()} in a loop. */
// default void onStart() throws InterruptedException {
// }
//
// default void onFailure() throws InterruptedException {
// }
//
// /** Called on the task thread, after we've interrupted/stopped calling {@link #runOneLoop()}. */
// default void onStop() throws InterruptedException {
// }
//
// /**
// * Called off the task thread, when we're trying to interrupt the task.
// *
// * Most threads shouldn't need this because they'll shut down
// * when we call thread.interrupt().
// */
// default void onInterrupt() {
// }
//
// default String getName() {
// String name = getClass().getSimpleName();
// // lambdas don't have simple names
// if (name.equals("")) {
// name = StringUtils.substringAfterLast(getClass().getName(), ".");
// }
// return name;
// }
// }
// Path: src/main/java/mirror/MirrorClient.java
import static mirror.Utils.withTimeout;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.time.Duration;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.util.concurrent.SettableFuture;
import io.grpc.ManagedChannel;
import io.grpc.stub.ClientCallStreamObserver;
import io.grpc.stub.ClientResponseObserver;
import io.grpc.stub.StreamObserver;
import mirror.MirrorGrpc.MirrorStub;
import mirror.tasks.TaskFactory;
import mirror.tasks.TaskLogic;
package mirror;
public class MirrorClient {
private static final Logger log = LoggerFactory.getLogger(MirrorClient.class);
private final MirrorPaths paths;
private final TaskFactory taskFactory;
private final ConnectionDetector detector;
private final FileWatcherFactory watcherFactory;
private final FileAccess fileAccess;
private final ChannelFactory channelFactory; | private volatile TaskLogic sessionStarter; |
stephenh/mirror | src/main/java/mirror/MirrorClient.java | // Path: src/main/java/mirror/Utils.java
// public static MirrorStub withTimeout(MirrorStub s) {
// // over VPN, ~100k files can take 30 seconds.
// return s.withDeadlineAfter(10, TimeUnit.MINUTES);
// }
//
// Path: src/main/java/mirror/tasks/TaskFactory.java
// public interface TaskFactory {
//
// default TaskHandle runTask(TaskLogic logic) {
// return runTask(logic, null);
// }
//
// TaskHandle runTask(TaskLogic logic, Runnable onFailure);
//
// void stopTask(TaskLogic logic);
//
// default TaskPool newTaskPool() {
// return new TaskPool(this);
// }
//
// }
//
// Path: src/main/java/mirror/tasks/TaskLogic.java
// public interface TaskLogic {
//
// /** Run one interaction, and return how long the task wants to sleep. */
// Duration runOneLoop() throws InterruptedException;
//
// /** Called on the task thread, before we start calling {@link #runOneLoop()} in a loop. */
// default void onStart() throws InterruptedException {
// }
//
// default void onFailure() throws InterruptedException {
// }
//
// /** Called on the task thread, after we've interrupted/stopped calling {@link #runOneLoop()}. */
// default void onStop() throws InterruptedException {
// }
//
// /**
// * Called off the task thread, when we're trying to interrupt the task.
// *
// * Most threads shouldn't need this because they'll shut down
// * when we call thread.interrupt().
// */
// default void onInterrupt() {
// }
//
// default String getName() {
// String name = getClass().getSimpleName();
// // lambdas don't have simple names
// if (name.equals("")) {
// name = StringUtils.substringAfterLast(getClass().getName(), ".");
// }
// return name;
// }
// }
| import static mirror.Utils.withTimeout;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.time.Duration;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.util.concurrent.SettableFuture;
import io.grpc.ManagedChannel;
import io.grpc.stub.ClientCallStreamObserver;
import io.grpc.stub.ClientResponseObserver;
import io.grpc.stub.StreamObserver;
import mirror.MirrorGrpc.MirrorStub;
import mirror.tasks.TaskFactory;
import mirror.tasks.TaskLogic; | package mirror;
public class MirrorClient {
private static final Logger log = LoggerFactory.getLogger(MirrorClient.class);
private final MirrorPaths paths;
private final TaskFactory taskFactory;
private final ConnectionDetector detector;
private final FileWatcherFactory watcherFactory;
private final FileAccess fileAccess;
private final ChannelFactory channelFactory;
private volatile TaskLogic sessionStarter;
private volatile MirrorSession session;
public MirrorClient(
MirrorPaths paths,
TaskFactory taskFactory,
ConnectionDetector detector,
FileWatcherFactory watcherFactory,
FileAccess fileAccess,
ChannelFactory channelFactory) {
this.paths = paths;
this.taskFactory = taskFactory;
this.detector = detector;
this.watcherFactory = watcherFactory;
this.fileAccess = fileAccess;
this.channelFactory = channelFactory;
}
/** Connects to the server and starts a sync session. */
public void startSession() throws InterruptedException {
CountDownLatch started = new CountDownLatch(1);
sessionStarter = new SessionStarter(channelFactory, started);
taskFactory.runTask(sessionStarter);
started.await();
}
private void startSession(ChannelFactory channelFactory, CountDownLatch onFailure) {
detector.blockUntilConnected();
log.info("Connected, starting session, version " + Mirror.getVersion());
ManagedChannel channel = channelFactory.newChannel();
MirrorStub stub = MirrorGrpc.newStub(channel).withCompression("gzip");
// 0. Do a time drift check
boolean outOfSync = logErrorIfTimeOutOfSync(stub);
if (outOfSync) {
return;
}
session = new MirrorSession(taskFactory, paths, fileAccess, watcherFactory);
session.addStoppedCallback(channel::shutdownNow);
// Automatically re-connect when we're disconnected
session.addStoppedCallback(() -> {
// Don't call startSession again directly, because then we'll start running
// our connection code on whatever thread is running this callback. Instead
// just signal our main client thread that it should try again.
onFailure.countDown();
});
// 1. see what our current state is
try {
List<Update> localState = session.calcInitialState();
log.info("Client has " + localState.size() + " paths");
// 2. send it to the server, so they can send back any stale/missing paths we have
SettableFuture<InitialSyncResponse> responseFuture = SettableFuture.create();
// Ideally this would be a blocking/sync call, but it looks like because
// one of our RPC methods is streaming, then this one is as well
InitialSyncRequest.Builder req = InitialSyncRequest
.newBuilder()
.setRemotePath(paths.remoteRoot.toString())
.setClientId(getClientId())
.setVersion(Mirror.getVersion())
.addAllState(localState);
paths.addParameters(req); | // Path: src/main/java/mirror/Utils.java
// public static MirrorStub withTimeout(MirrorStub s) {
// // over VPN, ~100k files can take 30 seconds.
// return s.withDeadlineAfter(10, TimeUnit.MINUTES);
// }
//
// Path: src/main/java/mirror/tasks/TaskFactory.java
// public interface TaskFactory {
//
// default TaskHandle runTask(TaskLogic logic) {
// return runTask(logic, null);
// }
//
// TaskHandle runTask(TaskLogic logic, Runnable onFailure);
//
// void stopTask(TaskLogic logic);
//
// default TaskPool newTaskPool() {
// return new TaskPool(this);
// }
//
// }
//
// Path: src/main/java/mirror/tasks/TaskLogic.java
// public interface TaskLogic {
//
// /** Run one interaction, and return how long the task wants to sleep. */
// Duration runOneLoop() throws InterruptedException;
//
// /** Called on the task thread, before we start calling {@link #runOneLoop()} in a loop. */
// default void onStart() throws InterruptedException {
// }
//
// default void onFailure() throws InterruptedException {
// }
//
// /** Called on the task thread, after we've interrupted/stopped calling {@link #runOneLoop()}. */
// default void onStop() throws InterruptedException {
// }
//
// /**
// * Called off the task thread, when we're trying to interrupt the task.
// *
// * Most threads shouldn't need this because they'll shut down
// * when we call thread.interrupt().
// */
// default void onInterrupt() {
// }
//
// default String getName() {
// String name = getClass().getSimpleName();
// // lambdas don't have simple names
// if (name.equals("")) {
// name = StringUtils.substringAfterLast(getClass().getName(), ".");
// }
// return name;
// }
// }
// Path: src/main/java/mirror/MirrorClient.java
import static mirror.Utils.withTimeout;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.time.Duration;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.util.concurrent.SettableFuture;
import io.grpc.ManagedChannel;
import io.grpc.stub.ClientCallStreamObserver;
import io.grpc.stub.ClientResponseObserver;
import io.grpc.stub.StreamObserver;
import mirror.MirrorGrpc.MirrorStub;
import mirror.tasks.TaskFactory;
import mirror.tasks.TaskLogic;
package mirror;
public class MirrorClient {
private static final Logger log = LoggerFactory.getLogger(MirrorClient.class);
private final MirrorPaths paths;
private final TaskFactory taskFactory;
private final ConnectionDetector detector;
private final FileWatcherFactory watcherFactory;
private final FileAccess fileAccess;
private final ChannelFactory channelFactory;
private volatile TaskLogic sessionStarter;
private volatile MirrorSession session;
public MirrorClient(
MirrorPaths paths,
TaskFactory taskFactory,
ConnectionDetector detector,
FileWatcherFactory watcherFactory,
FileAccess fileAccess,
ChannelFactory channelFactory) {
this.paths = paths;
this.taskFactory = taskFactory;
this.detector = detector;
this.watcherFactory = watcherFactory;
this.fileAccess = fileAccess;
this.channelFactory = channelFactory;
}
/** Connects to the server and starts a sync session. */
public void startSession() throws InterruptedException {
CountDownLatch started = new CountDownLatch(1);
sessionStarter = new SessionStarter(channelFactory, started);
taskFactory.runTask(sessionStarter);
started.await();
}
private void startSession(ChannelFactory channelFactory, CountDownLatch onFailure) {
detector.blockUntilConnected();
log.info("Connected, starting session, version " + Mirror.getVersion());
ManagedChannel channel = channelFactory.newChannel();
MirrorStub stub = MirrorGrpc.newStub(channel).withCompression("gzip");
// 0. Do a time drift check
boolean outOfSync = logErrorIfTimeOutOfSync(stub);
if (outOfSync) {
return;
}
session = new MirrorSession(taskFactory, paths, fileAccess, watcherFactory);
session.addStoppedCallback(channel::shutdownNow);
// Automatically re-connect when we're disconnected
session.addStoppedCallback(() -> {
// Don't call startSession again directly, because then we'll start running
// our connection code on whatever thread is running this callback. Instead
// just signal our main client thread that it should try again.
onFailure.countDown();
});
// 1. see what our current state is
try {
List<Update> localState = session.calcInitialState();
log.info("Client has " + localState.size() + " paths");
// 2. send it to the server, so they can send back any stale/missing paths we have
SettableFuture<InitialSyncResponse> responseFuture = SettableFuture.create();
// Ideally this would be a blocking/sync call, but it looks like because
// one of our RPC methods is streaming, then this one is as well
InitialSyncRequest.Builder req = InitialSyncRequest
.newBuilder()
.setRemotePath(paths.remoteRoot.toString())
.setClientId(getClientId())
.setVersion(Mirror.getVersion())
.addAllState(localState);
paths.addParameters(req); | withTimeout(stub).initialSync(req.build(), new StreamObserver<InitialSyncResponse>() { |
stephenh/mirror | src/main/java/mirror/MirrorSession.java | // Path: src/main/java/mirror/tasks/TaskFactory.java
// public interface TaskFactory {
//
// default TaskHandle runTask(TaskLogic logic) {
// return runTask(logic, null);
// }
//
// TaskHandle runTask(TaskLogic logic, Runnable onFailure);
//
// void stopTask(TaskLogic logic);
//
// default TaskPool newTaskPool() {
// return new TaskPool(this);
// }
//
// }
//
// Path: src/main/java/mirror/tasks/TaskLogic.java
// public interface TaskLogic {
//
// /** Run one interaction, and return how long the task wants to sleep. */
// Duration runOneLoop() throws InterruptedException;
//
// /** Called on the task thread, before we start calling {@link #runOneLoop()} in a loop. */
// default void onStart() throws InterruptedException {
// }
//
// default void onFailure() throws InterruptedException {
// }
//
// /** Called on the task thread, after we've interrupted/stopped calling {@link #runOneLoop()}. */
// default void onStop() throws InterruptedException {
// }
//
// /**
// * Called off the task thread, when we're trying to interrupt the task.
// *
// * Most threads shouldn't need this because they'll shut down
// * when we call thread.interrupt().
// */
// default void onInterrupt() {
// }
//
// default String getName() {
// String name = getClass().getSimpleName();
// // lambdas don't have simple names
// if (name.equals("")) {
// name = StringUtils.substringAfterLast(getClass().getName(), ".");
// }
// return name;
// }
// }
//
// Path: src/main/java/mirror/tasks/TaskPool.java
// public class TaskPool {
//
// private static final Logger log = LoggerFactory.getLogger(TaskPool.class);
// private final TaskFactory factory;
// private final List<TaskLogic> tasks = new CopyOnWriteArrayList<>();
// private final List<Runnable> callbacks = new CopyOnWriteArrayList<>();
// private final AtomicBoolean shutdown = new AtomicBoolean(false);
//
// public TaskPool(TaskFactory factory) {
// this.factory = factory;
// }
//
// public TaskHandle runTask(TaskLogic logic) {
// if (shutdown.get()) {
// throw new IllegalStateException("Pool is shutdown");
// }
// TaskHandle h = factory.runTask(logic, this::stopAllTasks);
// tasks.add(logic);
// return h;
// }
//
// public void stopTask(TaskLogic logic) {
// factory.stopTask(logic);
// tasks.remove(logic);
// }
//
// public void stopAllTasks() {
// // Several places call MirrorSession.stop when shutting down, so don't
// // error out if this is already shut down
// if (shutdown.compareAndSet(false, true)) {
// factory.runTask(new StopTasksInPool());
// }
// }
//
// public void addShutdownCallback(Runnable callback) {
// callbacks.add(callback);
// }
//
// private class StopTasksInPool implements TaskLogic {
// @Override
// public Duration runOneLoop() throws InterruptedException {
// new ArrayList<>(tasks).forEach(t -> {
// try {
// stopTask(t);
// } catch (Exception e) {
// log.error("Error calling callback", e);
// }
// });
// callbacks.forEach(r -> {
// try {
// r.run();
// } catch (Exception e) {
// log.error("Error calling callback", e);
// }
// });
// log.debug("All callbacks complete");
// return Duration.ofMillis(-1);
// }
// }
//
// }
| import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.grpc.StatusRuntimeException;
import mirror.tasks.TaskFactory;
import mirror.tasks.TaskLogic;
import mirror.tasks.TaskPool; | package mirror;
/**
* Represents a session of an initial sync plus on-going synchronization of
* our local file changes with a remote session.
*
* Note that the session is used on both the server and client, e.g. upon
* connection, the server will instantiate a MirrorSession to talk to the client,
* and the client will also instantiate it's own MirrorSession to talk to the
* server.
*
* Once the two MirrorSessions on each side are instantiated, the server
* and client are basically just peers using the same logic/implementation
* to share changes.
*/
public class MirrorSession {
private final Logger log = LoggerFactory.getLogger(MirrorSession.class); | // Path: src/main/java/mirror/tasks/TaskFactory.java
// public interface TaskFactory {
//
// default TaskHandle runTask(TaskLogic logic) {
// return runTask(logic, null);
// }
//
// TaskHandle runTask(TaskLogic logic, Runnable onFailure);
//
// void stopTask(TaskLogic logic);
//
// default TaskPool newTaskPool() {
// return new TaskPool(this);
// }
//
// }
//
// Path: src/main/java/mirror/tasks/TaskLogic.java
// public interface TaskLogic {
//
// /** Run one interaction, and return how long the task wants to sleep. */
// Duration runOneLoop() throws InterruptedException;
//
// /** Called on the task thread, before we start calling {@link #runOneLoop()} in a loop. */
// default void onStart() throws InterruptedException {
// }
//
// default void onFailure() throws InterruptedException {
// }
//
// /** Called on the task thread, after we've interrupted/stopped calling {@link #runOneLoop()}. */
// default void onStop() throws InterruptedException {
// }
//
// /**
// * Called off the task thread, when we're trying to interrupt the task.
// *
// * Most threads shouldn't need this because they'll shut down
// * when we call thread.interrupt().
// */
// default void onInterrupt() {
// }
//
// default String getName() {
// String name = getClass().getSimpleName();
// // lambdas don't have simple names
// if (name.equals("")) {
// name = StringUtils.substringAfterLast(getClass().getName(), ".");
// }
// return name;
// }
// }
//
// Path: src/main/java/mirror/tasks/TaskPool.java
// public class TaskPool {
//
// private static final Logger log = LoggerFactory.getLogger(TaskPool.class);
// private final TaskFactory factory;
// private final List<TaskLogic> tasks = new CopyOnWriteArrayList<>();
// private final List<Runnable> callbacks = new CopyOnWriteArrayList<>();
// private final AtomicBoolean shutdown = new AtomicBoolean(false);
//
// public TaskPool(TaskFactory factory) {
// this.factory = factory;
// }
//
// public TaskHandle runTask(TaskLogic logic) {
// if (shutdown.get()) {
// throw new IllegalStateException("Pool is shutdown");
// }
// TaskHandle h = factory.runTask(logic, this::stopAllTasks);
// tasks.add(logic);
// return h;
// }
//
// public void stopTask(TaskLogic logic) {
// factory.stopTask(logic);
// tasks.remove(logic);
// }
//
// public void stopAllTasks() {
// // Several places call MirrorSession.stop when shutting down, so don't
// // error out if this is already shut down
// if (shutdown.compareAndSet(false, true)) {
// factory.runTask(new StopTasksInPool());
// }
// }
//
// public void addShutdownCallback(Runnable callback) {
// callbacks.add(callback);
// }
//
// private class StopTasksInPool implements TaskLogic {
// @Override
// public Duration runOneLoop() throws InterruptedException {
// new ArrayList<>(tasks).forEach(t -> {
// try {
// stopTask(t);
// } catch (Exception e) {
// log.error("Error calling callback", e);
// }
// });
// callbacks.forEach(r -> {
// try {
// r.run();
// } catch (Exception e) {
// log.error("Error calling callback", e);
// }
// });
// log.debug("All callbacks complete");
// return Duration.ofMillis(-1);
// }
// }
//
// }
// Path: src/main/java/mirror/MirrorSession.java
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.grpc.StatusRuntimeException;
import mirror.tasks.TaskFactory;
import mirror.tasks.TaskLogic;
import mirror.tasks.TaskPool;
package mirror;
/**
* Represents a session of an initial sync plus on-going synchronization of
* our local file changes with a remote session.
*
* Note that the session is used on both the server and client, e.g. upon
* connection, the server will instantiate a MirrorSession to talk to the client,
* and the client will also instantiate it's own MirrorSession to talk to the
* server.
*
* Once the two MirrorSessions on each side are instantiated, the server
* and client are basically just peers using the same logic/implementation
* to share changes.
*/
public class MirrorSession {
private final Logger log = LoggerFactory.getLogger(MirrorSession.class); | private final TaskPool taskPool; |
stephenh/mirror | src/main/java/mirror/MirrorSession.java | // Path: src/main/java/mirror/tasks/TaskFactory.java
// public interface TaskFactory {
//
// default TaskHandle runTask(TaskLogic logic) {
// return runTask(logic, null);
// }
//
// TaskHandle runTask(TaskLogic logic, Runnable onFailure);
//
// void stopTask(TaskLogic logic);
//
// default TaskPool newTaskPool() {
// return new TaskPool(this);
// }
//
// }
//
// Path: src/main/java/mirror/tasks/TaskLogic.java
// public interface TaskLogic {
//
// /** Run one interaction, and return how long the task wants to sleep. */
// Duration runOneLoop() throws InterruptedException;
//
// /** Called on the task thread, before we start calling {@link #runOneLoop()} in a loop. */
// default void onStart() throws InterruptedException {
// }
//
// default void onFailure() throws InterruptedException {
// }
//
// /** Called on the task thread, after we've interrupted/stopped calling {@link #runOneLoop()}. */
// default void onStop() throws InterruptedException {
// }
//
// /**
// * Called off the task thread, when we're trying to interrupt the task.
// *
// * Most threads shouldn't need this because they'll shut down
// * when we call thread.interrupt().
// */
// default void onInterrupt() {
// }
//
// default String getName() {
// String name = getClass().getSimpleName();
// // lambdas don't have simple names
// if (name.equals("")) {
// name = StringUtils.substringAfterLast(getClass().getName(), ".");
// }
// return name;
// }
// }
//
// Path: src/main/java/mirror/tasks/TaskPool.java
// public class TaskPool {
//
// private static final Logger log = LoggerFactory.getLogger(TaskPool.class);
// private final TaskFactory factory;
// private final List<TaskLogic> tasks = new CopyOnWriteArrayList<>();
// private final List<Runnable> callbacks = new CopyOnWriteArrayList<>();
// private final AtomicBoolean shutdown = new AtomicBoolean(false);
//
// public TaskPool(TaskFactory factory) {
// this.factory = factory;
// }
//
// public TaskHandle runTask(TaskLogic logic) {
// if (shutdown.get()) {
// throw new IllegalStateException("Pool is shutdown");
// }
// TaskHandle h = factory.runTask(logic, this::stopAllTasks);
// tasks.add(logic);
// return h;
// }
//
// public void stopTask(TaskLogic logic) {
// factory.stopTask(logic);
// tasks.remove(logic);
// }
//
// public void stopAllTasks() {
// // Several places call MirrorSession.stop when shutting down, so don't
// // error out if this is already shut down
// if (shutdown.compareAndSet(false, true)) {
// factory.runTask(new StopTasksInPool());
// }
// }
//
// public void addShutdownCallback(Runnable callback) {
// callbacks.add(callback);
// }
//
// private class StopTasksInPool implements TaskLogic {
// @Override
// public Duration runOneLoop() throws InterruptedException {
// new ArrayList<>(tasks).forEach(t -> {
// try {
// stopTask(t);
// } catch (Exception e) {
// log.error("Error calling callback", e);
// }
// });
// callbacks.forEach(r -> {
// try {
// r.run();
// } catch (Exception e) {
// log.error("Error calling callback", e);
// }
// });
// log.debug("All callbacks complete");
// return Duration.ofMillis(-1);
// }
// }
//
// }
| import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.grpc.StatusRuntimeException;
import mirror.tasks.TaskFactory;
import mirror.tasks.TaskLogic;
import mirror.tasks.TaskPool; | package mirror;
/**
* Represents a session of an initial sync plus on-going synchronization of
* our local file changes with a remote session.
*
* Note that the session is used on both the server and client, e.g. upon
* connection, the server will instantiate a MirrorSession to talk to the client,
* and the client will also instantiate it's own MirrorSession to talk to the
* server.
*
* Once the two MirrorSessions on each side are instantiated, the server
* and client are basically just peers using the same logic/implementation
* to share changes.
*/
public class MirrorSession {
private final Logger log = LoggerFactory.getLogger(MirrorSession.class);
private final TaskPool taskPool;
private final FileAccess fileAccess;
private final Queues queues = new Queues();
private final QueueWatcher queueWatcher = new QueueWatcher(queues);
private final SaveToLocal saveToLocal;
private final FileWatcher fileWatcher;
private final UpdateTree tree;
private final SyncLogic syncLogic;
private volatile SaveToRemote saveToRemote;
private volatile OutgoingConnection outgoingChanges;
| // Path: src/main/java/mirror/tasks/TaskFactory.java
// public interface TaskFactory {
//
// default TaskHandle runTask(TaskLogic logic) {
// return runTask(logic, null);
// }
//
// TaskHandle runTask(TaskLogic logic, Runnable onFailure);
//
// void stopTask(TaskLogic logic);
//
// default TaskPool newTaskPool() {
// return new TaskPool(this);
// }
//
// }
//
// Path: src/main/java/mirror/tasks/TaskLogic.java
// public interface TaskLogic {
//
// /** Run one interaction, and return how long the task wants to sleep. */
// Duration runOneLoop() throws InterruptedException;
//
// /** Called on the task thread, before we start calling {@link #runOneLoop()} in a loop. */
// default void onStart() throws InterruptedException {
// }
//
// default void onFailure() throws InterruptedException {
// }
//
// /** Called on the task thread, after we've interrupted/stopped calling {@link #runOneLoop()}. */
// default void onStop() throws InterruptedException {
// }
//
// /**
// * Called off the task thread, when we're trying to interrupt the task.
// *
// * Most threads shouldn't need this because they'll shut down
// * when we call thread.interrupt().
// */
// default void onInterrupt() {
// }
//
// default String getName() {
// String name = getClass().getSimpleName();
// // lambdas don't have simple names
// if (name.equals("")) {
// name = StringUtils.substringAfterLast(getClass().getName(), ".");
// }
// return name;
// }
// }
//
// Path: src/main/java/mirror/tasks/TaskPool.java
// public class TaskPool {
//
// private static final Logger log = LoggerFactory.getLogger(TaskPool.class);
// private final TaskFactory factory;
// private final List<TaskLogic> tasks = new CopyOnWriteArrayList<>();
// private final List<Runnable> callbacks = new CopyOnWriteArrayList<>();
// private final AtomicBoolean shutdown = new AtomicBoolean(false);
//
// public TaskPool(TaskFactory factory) {
// this.factory = factory;
// }
//
// public TaskHandle runTask(TaskLogic logic) {
// if (shutdown.get()) {
// throw new IllegalStateException("Pool is shutdown");
// }
// TaskHandle h = factory.runTask(logic, this::stopAllTasks);
// tasks.add(logic);
// return h;
// }
//
// public void stopTask(TaskLogic logic) {
// factory.stopTask(logic);
// tasks.remove(logic);
// }
//
// public void stopAllTasks() {
// // Several places call MirrorSession.stop when shutting down, so don't
// // error out if this is already shut down
// if (shutdown.compareAndSet(false, true)) {
// factory.runTask(new StopTasksInPool());
// }
// }
//
// public void addShutdownCallback(Runnable callback) {
// callbacks.add(callback);
// }
//
// private class StopTasksInPool implements TaskLogic {
// @Override
// public Duration runOneLoop() throws InterruptedException {
// new ArrayList<>(tasks).forEach(t -> {
// try {
// stopTask(t);
// } catch (Exception e) {
// log.error("Error calling callback", e);
// }
// });
// callbacks.forEach(r -> {
// try {
// r.run();
// } catch (Exception e) {
// log.error("Error calling callback", e);
// }
// });
// log.debug("All callbacks complete");
// return Duration.ofMillis(-1);
// }
// }
//
// }
// Path: src/main/java/mirror/MirrorSession.java
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.grpc.StatusRuntimeException;
import mirror.tasks.TaskFactory;
import mirror.tasks.TaskLogic;
import mirror.tasks.TaskPool;
package mirror;
/**
* Represents a session of an initial sync plus on-going synchronization of
* our local file changes with a remote session.
*
* Note that the session is used on both the server and client, e.g. upon
* connection, the server will instantiate a MirrorSession to talk to the client,
* and the client will also instantiate it's own MirrorSession to talk to the
* server.
*
* Once the two MirrorSessions on each side are instantiated, the server
* and client are basically just peers using the same logic/implementation
* to share changes.
*/
public class MirrorSession {
private final Logger log = LoggerFactory.getLogger(MirrorSession.class);
private final TaskPool taskPool;
private final FileAccess fileAccess;
private final Queues queues = new Queues();
private final QueueWatcher queueWatcher = new QueueWatcher(queues);
private final SaveToLocal saveToLocal;
private final FileWatcher fileWatcher;
private final UpdateTree tree;
private final SyncLogic syncLogic;
private volatile SaveToRemote saveToRemote;
private volatile OutgoingConnection outgoingChanges;
| public MirrorSession(TaskFactory taskFactory, MirrorPaths paths, FileAccess fileAccess, FileWatcherFactory fileWatcherFactory) { |
stephenh/mirror | src/main/java/mirror/MirrorSession.java | // Path: src/main/java/mirror/tasks/TaskFactory.java
// public interface TaskFactory {
//
// default TaskHandle runTask(TaskLogic logic) {
// return runTask(logic, null);
// }
//
// TaskHandle runTask(TaskLogic logic, Runnable onFailure);
//
// void stopTask(TaskLogic logic);
//
// default TaskPool newTaskPool() {
// return new TaskPool(this);
// }
//
// }
//
// Path: src/main/java/mirror/tasks/TaskLogic.java
// public interface TaskLogic {
//
// /** Run one interaction, and return how long the task wants to sleep. */
// Duration runOneLoop() throws InterruptedException;
//
// /** Called on the task thread, before we start calling {@link #runOneLoop()} in a loop. */
// default void onStart() throws InterruptedException {
// }
//
// default void onFailure() throws InterruptedException {
// }
//
// /** Called on the task thread, after we've interrupted/stopped calling {@link #runOneLoop()}. */
// default void onStop() throws InterruptedException {
// }
//
// /**
// * Called off the task thread, when we're trying to interrupt the task.
// *
// * Most threads shouldn't need this because they'll shut down
// * when we call thread.interrupt().
// */
// default void onInterrupt() {
// }
//
// default String getName() {
// String name = getClass().getSimpleName();
// // lambdas don't have simple names
// if (name.equals("")) {
// name = StringUtils.substringAfterLast(getClass().getName(), ".");
// }
// return name;
// }
// }
//
// Path: src/main/java/mirror/tasks/TaskPool.java
// public class TaskPool {
//
// private static final Logger log = LoggerFactory.getLogger(TaskPool.class);
// private final TaskFactory factory;
// private final List<TaskLogic> tasks = new CopyOnWriteArrayList<>();
// private final List<Runnable> callbacks = new CopyOnWriteArrayList<>();
// private final AtomicBoolean shutdown = new AtomicBoolean(false);
//
// public TaskPool(TaskFactory factory) {
// this.factory = factory;
// }
//
// public TaskHandle runTask(TaskLogic logic) {
// if (shutdown.get()) {
// throw new IllegalStateException("Pool is shutdown");
// }
// TaskHandle h = factory.runTask(logic, this::stopAllTasks);
// tasks.add(logic);
// return h;
// }
//
// public void stopTask(TaskLogic logic) {
// factory.stopTask(logic);
// tasks.remove(logic);
// }
//
// public void stopAllTasks() {
// // Several places call MirrorSession.stop when shutting down, so don't
// // error out if this is already shut down
// if (shutdown.compareAndSet(false, true)) {
// factory.runTask(new StopTasksInPool());
// }
// }
//
// public void addShutdownCallback(Runnable callback) {
// callbacks.add(callback);
// }
//
// private class StopTasksInPool implements TaskLogic {
// @Override
// public Duration runOneLoop() throws InterruptedException {
// new ArrayList<>(tasks).forEach(t -> {
// try {
// stopTask(t);
// } catch (Exception e) {
// log.error("Error calling callback", e);
// }
// });
// callbacks.forEach(r -> {
// try {
// r.run();
// } catch (Exception e) {
// log.error("Error calling callback", e);
// }
// });
// log.debug("All callbacks complete");
// return Duration.ofMillis(-1);
// }
// }
//
// }
| import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.grpc.StatusRuntimeException;
import mirror.tasks.TaskFactory;
import mirror.tasks.TaskLogic;
import mirror.tasks.TaskPool; | });
return seedRemote;
}
public void addInitialRemoteUpdates(List<Update> remoteInitialUpdates) {
remoteInitialUpdates.forEach(u -> {
// if a file, mark it has an initial sync, so we know not to save it
// it until we get the real update with the data filled in
if (UpdateTree.isFile(u)) {
u = u.toBuilder().setData(UpdateTree.initialSyncMarker).build();
}
tree.addRemote(u);
});
}
public void diffAndStartPolling(OutgoingConnection outgoingChanges) {
this.outgoingChanges = outgoingChanges;
start(syncLogic);
saveToRemote = new SaveToRemote(queues, fileAccess, outgoingChanges);
start(saveToRemote);
}
public void stop() {
log.info("Stopping session");
// this won't block; could potentially add a CountDownLatch
taskPool.stopAllTasks();
}
| // Path: src/main/java/mirror/tasks/TaskFactory.java
// public interface TaskFactory {
//
// default TaskHandle runTask(TaskLogic logic) {
// return runTask(logic, null);
// }
//
// TaskHandle runTask(TaskLogic logic, Runnable onFailure);
//
// void stopTask(TaskLogic logic);
//
// default TaskPool newTaskPool() {
// return new TaskPool(this);
// }
//
// }
//
// Path: src/main/java/mirror/tasks/TaskLogic.java
// public interface TaskLogic {
//
// /** Run one interaction, and return how long the task wants to sleep. */
// Duration runOneLoop() throws InterruptedException;
//
// /** Called on the task thread, before we start calling {@link #runOneLoop()} in a loop. */
// default void onStart() throws InterruptedException {
// }
//
// default void onFailure() throws InterruptedException {
// }
//
// /** Called on the task thread, after we've interrupted/stopped calling {@link #runOneLoop()}. */
// default void onStop() throws InterruptedException {
// }
//
// /**
// * Called off the task thread, when we're trying to interrupt the task.
// *
// * Most threads shouldn't need this because they'll shut down
// * when we call thread.interrupt().
// */
// default void onInterrupt() {
// }
//
// default String getName() {
// String name = getClass().getSimpleName();
// // lambdas don't have simple names
// if (name.equals("")) {
// name = StringUtils.substringAfterLast(getClass().getName(), ".");
// }
// return name;
// }
// }
//
// Path: src/main/java/mirror/tasks/TaskPool.java
// public class TaskPool {
//
// private static final Logger log = LoggerFactory.getLogger(TaskPool.class);
// private final TaskFactory factory;
// private final List<TaskLogic> tasks = new CopyOnWriteArrayList<>();
// private final List<Runnable> callbacks = new CopyOnWriteArrayList<>();
// private final AtomicBoolean shutdown = new AtomicBoolean(false);
//
// public TaskPool(TaskFactory factory) {
// this.factory = factory;
// }
//
// public TaskHandle runTask(TaskLogic logic) {
// if (shutdown.get()) {
// throw new IllegalStateException("Pool is shutdown");
// }
// TaskHandle h = factory.runTask(logic, this::stopAllTasks);
// tasks.add(logic);
// return h;
// }
//
// public void stopTask(TaskLogic logic) {
// factory.stopTask(logic);
// tasks.remove(logic);
// }
//
// public void stopAllTasks() {
// // Several places call MirrorSession.stop when shutting down, so don't
// // error out if this is already shut down
// if (shutdown.compareAndSet(false, true)) {
// factory.runTask(new StopTasksInPool());
// }
// }
//
// public void addShutdownCallback(Runnable callback) {
// callbacks.add(callback);
// }
//
// private class StopTasksInPool implements TaskLogic {
// @Override
// public Duration runOneLoop() throws InterruptedException {
// new ArrayList<>(tasks).forEach(t -> {
// try {
// stopTask(t);
// } catch (Exception e) {
// log.error("Error calling callback", e);
// }
// });
// callbacks.forEach(r -> {
// try {
// r.run();
// } catch (Exception e) {
// log.error("Error calling callback", e);
// }
// });
// log.debug("All callbacks complete");
// return Duration.ofMillis(-1);
// }
// }
//
// }
// Path: src/main/java/mirror/MirrorSession.java
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.grpc.StatusRuntimeException;
import mirror.tasks.TaskFactory;
import mirror.tasks.TaskLogic;
import mirror.tasks.TaskPool;
});
return seedRemote;
}
public void addInitialRemoteUpdates(List<Update> remoteInitialUpdates) {
remoteInitialUpdates.forEach(u -> {
// if a file, mark it has an initial sync, so we know not to save it
// it until we get the real update with the data filled in
if (UpdateTree.isFile(u)) {
u = u.toBuilder().setData(UpdateTree.initialSyncMarker).build();
}
tree.addRemote(u);
});
}
public void diffAndStartPolling(OutgoingConnection outgoingChanges) {
this.outgoingChanges = outgoingChanges;
start(syncLogic);
saveToRemote = new SaveToRemote(queues, fileAccess, outgoingChanges);
start(saveToRemote);
}
public void stop() {
log.info("Stopping session");
// this won't block; could potentially add a CountDownLatch
taskPool.stopAllTasks();
}
| private void start(TaskLogic logic) { |
stephenh/mirror | src/test/java/mirror/BigIntegrationTest.java | // Path: src/test/java/mirror/TestUtils.java
// public static String readFile(final File file) throws IOException {
// return FileUtils.readFileToString(file, UTF_8);
// }
//
// Path: src/test/java/mirror/TestUtils.java
// public static void writeFile(final File file, final String data) throws IOException {
// FileUtils.writeStringToFile(file, data, UTF_8);
// }
//
// Path: src/main/java/mirror/tasks/TaskFactory.java
// public interface TaskFactory {
//
// default TaskHandle runTask(TaskLogic logic) {
// return runTask(logic, null);
// }
//
// TaskHandle runTask(TaskLogic logic, Runnable onFailure);
//
// void stopTask(TaskLogic logic);
//
// default TaskPool newTaskPool() {
// return new TaskPool(this);
// }
//
// }
//
// Path: src/main/java/mirror/tasks/ThreadBasedTaskFactory.java
// public class ThreadBasedTaskFactory implements TaskFactory {
//
// private final ConcurrentHashMap<TaskLogic, ThreadBasedTask> tasks = new ConcurrentHashMap<>();
//
// @Override
// public TaskHandle runTask(TaskLogic logic, Runnable onFailure) {
// ThreadBasedTask task = new ThreadBasedTask(logic, onFailure, () -> {
// // we don't need to call stopTask(logic) or task.stop because the task is already stopping,
// // we just to ensure we remove this entry from our map to avoid memory leaks
// tasks.remove(logic);
// });
// tasks.put(logic, task);
// task.start();
// return () -> stopTask(logic);
// }
//
// // Note that this method isn't synchronized, as while shutting down one task,
// // while we block on task.stop completing, the task might ask us to shut down
// // one of it's child tasks, but from it's own thread, which would block.
// @Override
// public void stopTask(TaskLogic logic) {
// ThreadBasedTask task = tasks.get(logic);
// if (task != null) {
// tasks.remove(logic);
// task.stop();
// }
// }
//
// }
| import static mirror.TestUtils.readFile;
import static mirror.TestUtils.writeFile;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import java.io.File;
import java.util.ArrayList;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.grpc.Server;
import io.grpc.inprocess.InProcessChannelBuilder;
import io.grpc.inprocess.InProcessServerBuilder;
import mirror.tasks.TaskFactory;
import mirror.tasks.ThreadBasedTaskFactory; | private MirrorClient client;
@Before
public void clearFiles() throws Exception {
FileUtils.deleteDirectory(integrationTestDir);
integrationTestDir.mkdirs();
root1.mkdirs();
root2.mkdirs();
}
@After
public void shutdown() throws Exception {
// rpc.awaitTermination();
if (client != null) {
log.info("stopping client");
client.stop();
}
if (rpc != null) {
log.info("stopping server");
rpc.shutdown();
}
rpc.shutdown();
rpc.awaitTermination();
}
@Test
public void testLotsOfFiles() throws Exception {
for (int i = 0; i < 500; i++) {
for (int j = 0; j < 100; j++) {
for (int k = 0; k < 10; k++) { | // Path: src/test/java/mirror/TestUtils.java
// public static String readFile(final File file) throws IOException {
// return FileUtils.readFileToString(file, UTF_8);
// }
//
// Path: src/test/java/mirror/TestUtils.java
// public static void writeFile(final File file, final String data) throws IOException {
// FileUtils.writeStringToFile(file, data, UTF_8);
// }
//
// Path: src/main/java/mirror/tasks/TaskFactory.java
// public interface TaskFactory {
//
// default TaskHandle runTask(TaskLogic logic) {
// return runTask(logic, null);
// }
//
// TaskHandle runTask(TaskLogic logic, Runnable onFailure);
//
// void stopTask(TaskLogic logic);
//
// default TaskPool newTaskPool() {
// return new TaskPool(this);
// }
//
// }
//
// Path: src/main/java/mirror/tasks/ThreadBasedTaskFactory.java
// public class ThreadBasedTaskFactory implements TaskFactory {
//
// private final ConcurrentHashMap<TaskLogic, ThreadBasedTask> tasks = new ConcurrentHashMap<>();
//
// @Override
// public TaskHandle runTask(TaskLogic logic, Runnable onFailure) {
// ThreadBasedTask task = new ThreadBasedTask(logic, onFailure, () -> {
// // we don't need to call stopTask(logic) or task.stop because the task is already stopping,
// // we just to ensure we remove this entry from our map to avoid memory leaks
// tasks.remove(logic);
// });
// tasks.put(logic, task);
// task.start();
// return () -> stopTask(logic);
// }
//
// // Note that this method isn't synchronized, as while shutting down one task,
// // while we block on task.stop completing, the task might ask us to shut down
// // one of it's child tasks, but from it's own thread, which would block.
// @Override
// public void stopTask(TaskLogic logic) {
// ThreadBasedTask task = tasks.get(logic);
// if (task != null) {
// tasks.remove(logic);
// task.stop();
// }
// }
//
// }
// Path: src/test/java/mirror/BigIntegrationTest.java
import static mirror.TestUtils.readFile;
import static mirror.TestUtils.writeFile;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import java.io.File;
import java.util.ArrayList;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.grpc.Server;
import io.grpc.inprocess.InProcessChannelBuilder;
import io.grpc.inprocess.InProcessServerBuilder;
import mirror.tasks.TaskFactory;
import mirror.tasks.ThreadBasedTaskFactory;
private MirrorClient client;
@Before
public void clearFiles() throws Exception {
FileUtils.deleteDirectory(integrationTestDir);
integrationTestDir.mkdirs();
root1.mkdirs();
root2.mkdirs();
}
@After
public void shutdown() throws Exception {
// rpc.awaitTermination();
if (client != null) {
log.info("stopping client");
client.stop();
}
if (rpc != null) {
log.info("stopping server");
rpc.shutdown();
}
rpc.shutdown();
rpc.awaitTermination();
}
@Test
public void testLotsOfFiles() throws Exception {
for (int i = 0; i < 500; i++) {
for (int j = 0; j < 100; j++) {
for (int k = 0; k < 10; k++) { | writeFile(new File(root1, "project" + i + "/dir" + j + "/file-" + k + ".txt"), "abc"); |
stephenh/mirror | src/test/java/mirror/BigIntegrationTest.java | // Path: src/test/java/mirror/TestUtils.java
// public static String readFile(final File file) throws IOException {
// return FileUtils.readFileToString(file, UTF_8);
// }
//
// Path: src/test/java/mirror/TestUtils.java
// public static void writeFile(final File file, final String data) throws IOException {
// FileUtils.writeStringToFile(file, data, UTF_8);
// }
//
// Path: src/main/java/mirror/tasks/TaskFactory.java
// public interface TaskFactory {
//
// default TaskHandle runTask(TaskLogic logic) {
// return runTask(logic, null);
// }
//
// TaskHandle runTask(TaskLogic logic, Runnable onFailure);
//
// void stopTask(TaskLogic logic);
//
// default TaskPool newTaskPool() {
// return new TaskPool(this);
// }
//
// }
//
// Path: src/main/java/mirror/tasks/ThreadBasedTaskFactory.java
// public class ThreadBasedTaskFactory implements TaskFactory {
//
// private final ConcurrentHashMap<TaskLogic, ThreadBasedTask> tasks = new ConcurrentHashMap<>();
//
// @Override
// public TaskHandle runTask(TaskLogic logic, Runnable onFailure) {
// ThreadBasedTask task = new ThreadBasedTask(logic, onFailure, () -> {
// // we don't need to call stopTask(logic) or task.stop because the task is already stopping,
// // we just to ensure we remove this entry from our map to avoid memory leaks
// tasks.remove(logic);
// });
// tasks.put(logic, task);
// task.start();
// return () -> stopTask(logic);
// }
//
// // Note that this method isn't synchronized, as while shutting down one task,
// // while we block on task.stop completing, the task might ask us to shut down
// // one of it's child tasks, but from it's own thread, which would block.
// @Override
// public void stopTask(TaskLogic logic) {
// ThreadBasedTask task = tasks.get(logic);
// if (task != null) {
// tasks.remove(logic);
// task.stop();
// }
// }
//
// }
| import static mirror.TestUtils.readFile;
import static mirror.TestUtils.writeFile;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import java.io.File;
import java.util.ArrayList;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.grpc.Server;
import io.grpc.inprocess.InProcessChannelBuilder;
import io.grpc.inprocess.InProcessServerBuilder;
import mirror.tasks.TaskFactory;
import mirror.tasks.ThreadBasedTaskFactory; | @After
public void shutdown() throws Exception {
// rpc.awaitTermination();
if (client != null) {
log.info("stopping client");
client.stop();
}
if (rpc != null) {
log.info("stopping server");
rpc.shutdown();
}
rpc.shutdown();
rpc.awaitTermination();
}
@Test
public void testLotsOfFiles() throws Exception {
for (int i = 0; i < 500; i++) {
for (int j = 0; j < 100; j++) {
for (int k = 0; k < 10; k++) {
writeFile(new File(root1, "project" + i + "/dir" + j + "/file-" + k + ".txt"), "abc");
}
}
}
startMirror();
sleep();
sleep();
sleep();
sleep();
sleep(); | // Path: src/test/java/mirror/TestUtils.java
// public static String readFile(final File file) throws IOException {
// return FileUtils.readFileToString(file, UTF_8);
// }
//
// Path: src/test/java/mirror/TestUtils.java
// public static void writeFile(final File file, final String data) throws IOException {
// FileUtils.writeStringToFile(file, data, UTF_8);
// }
//
// Path: src/main/java/mirror/tasks/TaskFactory.java
// public interface TaskFactory {
//
// default TaskHandle runTask(TaskLogic logic) {
// return runTask(logic, null);
// }
//
// TaskHandle runTask(TaskLogic logic, Runnable onFailure);
//
// void stopTask(TaskLogic logic);
//
// default TaskPool newTaskPool() {
// return new TaskPool(this);
// }
//
// }
//
// Path: src/main/java/mirror/tasks/ThreadBasedTaskFactory.java
// public class ThreadBasedTaskFactory implements TaskFactory {
//
// private final ConcurrentHashMap<TaskLogic, ThreadBasedTask> tasks = new ConcurrentHashMap<>();
//
// @Override
// public TaskHandle runTask(TaskLogic logic, Runnable onFailure) {
// ThreadBasedTask task = new ThreadBasedTask(logic, onFailure, () -> {
// // we don't need to call stopTask(logic) or task.stop because the task is already stopping,
// // we just to ensure we remove this entry from our map to avoid memory leaks
// tasks.remove(logic);
// });
// tasks.put(logic, task);
// task.start();
// return () -> stopTask(logic);
// }
//
// // Note that this method isn't synchronized, as while shutting down one task,
// // while we block on task.stop completing, the task might ask us to shut down
// // one of it's child tasks, but from it's own thread, which would block.
// @Override
// public void stopTask(TaskLogic logic) {
// ThreadBasedTask task = tasks.get(logic);
// if (task != null) {
// tasks.remove(logic);
// task.stop();
// }
// }
//
// }
// Path: src/test/java/mirror/BigIntegrationTest.java
import static mirror.TestUtils.readFile;
import static mirror.TestUtils.writeFile;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import java.io.File;
import java.util.ArrayList;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.grpc.Server;
import io.grpc.inprocess.InProcessChannelBuilder;
import io.grpc.inprocess.InProcessServerBuilder;
import mirror.tasks.TaskFactory;
import mirror.tasks.ThreadBasedTaskFactory;
@After
public void shutdown() throws Exception {
// rpc.awaitTermination();
if (client != null) {
log.info("stopping client");
client.stop();
}
if (rpc != null) {
log.info("stopping server");
rpc.shutdown();
}
rpc.shutdown();
rpc.awaitTermination();
}
@Test
public void testLotsOfFiles() throws Exception {
for (int i = 0; i < 500; i++) {
for (int j = 0; j < 100; j++) {
for (int k = 0; k < 10; k++) {
writeFile(new File(root1, "project" + i + "/dir" + j + "/file-" + k + ".txt"), "abc");
}
}
}
startMirror();
sleep();
sleep();
sleep();
sleep();
sleep(); | assertThat(readFile(new File(root2, "foo.txt")), is("abc")); |
stephenh/mirror | src/test/java/mirror/BigIntegrationTest.java | // Path: src/test/java/mirror/TestUtils.java
// public static String readFile(final File file) throws IOException {
// return FileUtils.readFileToString(file, UTF_8);
// }
//
// Path: src/test/java/mirror/TestUtils.java
// public static void writeFile(final File file, final String data) throws IOException {
// FileUtils.writeStringToFile(file, data, UTF_8);
// }
//
// Path: src/main/java/mirror/tasks/TaskFactory.java
// public interface TaskFactory {
//
// default TaskHandle runTask(TaskLogic logic) {
// return runTask(logic, null);
// }
//
// TaskHandle runTask(TaskLogic logic, Runnable onFailure);
//
// void stopTask(TaskLogic logic);
//
// default TaskPool newTaskPool() {
// return new TaskPool(this);
// }
//
// }
//
// Path: src/main/java/mirror/tasks/ThreadBasedTaskFactory.java
// public class ThreadBasedTaskFactory implements TaskFactory {
//
// private final ConcurrentHashMap<TaskLogic, ThreadBasedTask> tasks = new ConcurrentHashMap<>();
//
// @Override
// public TaskHandle runTask(TaskLogic logic, Runnable onFailure) {
// ThreadBasedTask task = new ThreadBasedTask(logic, onFailure, () -> {
// // we don't need to call stopTask(logic) or task.stop because the task is already stopping,
// // we just to ensure we remove this entry from our map to avoid memory leaks
// tasks.remove(logic);
// });
// tasks.put(logic, task);
// task.start();
// return () -> stopTask(logic);
// }
//
// // Note that this method isn't synchronized, as while shutting down one task,
// // while we block on task.stop completing, the task might ask us to shut down
// // one of it's child tasks, but from it's own thread, which would block.
// @Override
// public void stopTask(TaskLogic logic) {
// ThreadBasedTask task = tasks.get(logic);
// if (task != null) {
// tasks.remove(logic);
// task.stop();
// }
// }
//
// }
| import static mirror.TestUtils.readFile;
import static mirror.TestUtils.writeFile;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import java.io.File;
import java.util.ArrayList;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.grpc.Server;
import io.grpc.inprocess.InProcessChannelBuilder;
import io.grpc.inprocess.InProcessServerBuilder;
import mirror.tasks.TaskFactory;
import mirror.tasks.ThreadBasedTaskFactory; | }
if (rpc != null) {
log.info("stopping server");
rpc.shutdown();
}
rpc.shutdown();
rpc.awaitTermination();
}
@Test
public void testLotsOfFiles() throws Exception {
for (int i = 0; i < 500; i++) {
for (int j = 0; j < 100; j++) {
for (int k = 0; k < 10; k++) {
writeFile(new File(root1, "project" + i + "/dir" + j + "/file-" + k + ".txt"), "abc");
}
}
}
startMirror();
sleep();
sleep();
sleep();
sleep();
sleep();
assertThat(readFile(new File(root2, "foo.txt")), is("abc"));
}
private void startMirror() throws Exception {
// server
int port = nextPort++; | // Path: src/test/java/mirror/TestUtils.java
// public static String readFile(final File file) throws IOException {
// return FileUtils.readFileToString(file, UTF_8);
// }
//
// Path: src/test/java/mirror/TestUtils.java
// public static void writeFile(final File file, final String data) throws IOException {
// FileUtils.writeStringToFile(file, data, UTF_8);
// }
//
// Path: src/main/java/mirror/tasks/TaskFactory.java
// public interface TaskFactory {
//
// default TaskHandle runTask(TaskLogic logic) {
// return runTask(logic, null);
// }
//
// TaskHandle runTask(TaskLogic logic, Runnable onFailure);
//
// void stopTask(TaskLogic logic);
//
// default TaskPool newTaskPool() {
// return new TaskPool(this);
// }
//
// }
//
// Path: src/main/java/mirror/tasks/ThreadBasedTaskFactory.java
// public class ThreadBasedTaskFactory implements TaskFactory {
//
// private final ConcurrentHashMap<TaskLogic, ThreadBasedTask> tasks = new ConcurrentHashMap<>();
//
// @Override
// public TaskHandle runTask(TaskLogic logic, Runnable onFailure) {
// ThreadBasedTask task = new ThreadBasedTask(logic, onFailure, () -> {
// // we don't need to call stopTask(logic) or task.stop because the task is already stopping,
// // we just to ensure we remove this entry from our map to avoid memory leaks
// tasks.remove(logic);
// });
// tasks.put(logic, task);
// task.start();
// return () -> stopTask(logic);
// }
//
// // Note that this method isn't synchronized, as while shutting down one task,
// // while we block on task.stop completing, the task might ask us to shut down
// // one of it's child tasks, but from it's own thread, which would block.
// @Override
// public void stopTask(TaskLogic logic) {
// ThreadBasedTask task = tasks.get(logic);
// if (task != null) {
// tasks.remove(logic);
// task.stop();
// }
// }
//
// }
// Path: src/test/java/mirror/BigIntegrationTest.java
import static mirror.TestUtils.readFile;
import static mirror.TestUtils.writeFile;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import java.io.File;
import java.util.ArrayList;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.grpc.Server;
import io.grpc.inprocess.InProcessChannelBuilder;
import io.grpc.inprocess.InProcessServerBuilder;
import mirror.tasks.TaskFactory;
import mirror.tasks.ThreadBasedTaskFactory;
}
if (rpc != null) {
log.info("stopping server");
rpc.shutdown();
}
rpc.shutdown();
rpc.awaitTermination();
}
@Test
public void testLotsOfFiles() throws Exception {
for (int i = 0; i < 500; i++) {
for (int j = 0; j < 100; j++) {
for (int k = 0; k < 10; k++) {
writeFile(new File(root1, "project" + i + "/dir" + j + "/file-" + k + ".txt"), "abc");
}
}
}
startMirror();
sleep();
sleep();
sleep();
sleep();
sleep();
assertThat(readFile(new File(root2, "foo.txt")), is("abc"));
}
private void startMirror() throws Exception {
// server
int port = nextPort++; | TaskFactory serverTaskFactory = new ThreadBasedTaskFactory(); |
stephenh/mirror | src/test/java/mirror/BigIntegrationTest.java | // Path: src/test/java/mirror/TestUtils.java
// public static String readFile(final File file) throws IOException {
// return FileUtils.readFileToString(file, UTF_8);
// }
//
// Path: src/test/java/mirror/TestUtils.java
// public static void writeFile(final File file, final String data) throws IOException {
// FileUtils.writeStringToFile(file, data, UTF_8);
// }
//
// Path: src/main/java/mirror/tasks/TaskFactory.java
// public interface TaskFactory {
//
// default TaskHandle runTask(TaskLogic logic) {
// return runTask(logic, null);
// }
//
// TaskHandle runTask(TaskLogic logic, Runnable onFailure);
//
// void stopTask(TaskLogic logic);
//
// default TaskPool newTaskPool() {
// return new TaskPool(this);
// }
//
// }
//
// Path: src/main/java/mirror/tasks/ThreadBasedTaskFactory.java
// public class ThreadBasedTaskFactory implements TaskFactory {
//
// private final ConcurrentHashMap<TaskLogic, ThreadBasedTask> tasks = new ConcurrentHashMap<>();
//
// @Override
// public TaskHandle runTask(TaskLogic logic, Runnable onFailure) {
// ThreadBasedTask task = new ThreadBasedTask(logic, onFailure, () -> {
// // we don't need to call stopTask(logic) or task.stop because the task is already stopping,
// // we just to ensure we remove this entry from our map to avoid memory leaks
// tasks.remove(logic);
// });
// tasks.put(logic, task);
// task.start();
// return () -> stopTask(logic);
// }
//
// // Note that this method isn't synchronized, as while shutting down one task,
// // while we block on task.stop completing, the task might ask us to shut down
// // one of it's child tasks, but from it's own thread, which would block.
// @Override
// public void stopTask(TaskLogic logic) {
// ThreadBasedTask task = tasks.get(logic);
// if (task != null) {
// tasks.remove(logic);
// task.stop();
// }
// }
//
// }
| import static mirror.TestUtils.readFile;
import static mirror.TestUtils.writeFile;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import java.io.File;
import java.util.ArrayList;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.grpc.Server;
import io.grpc.inprocess.InProcessChannelBuilder;
import io.grpc.inprocess.InProcessServerBuilder;
import mirror.tasks.TaskFactory;
import mirror.tasks.ThreadBasedTaskFactory; | }
if (rpc != null) {
log.info("stopping server");
rpc.shutdown();
}
rpc.shutdown();
rpc.awaitTermination();
}
@Test
public void testLotsOfFiles() throws Exception {
for (int i = 0; i < 500; i++) {
for (int j = 0; j < 100; j++) {
for (int k = 0; k < 10; k++) {
writeFile(new File(root1, "project" + i + "/dir" + j + "/file-" + k + ".txt"), "abc");
}
}
}
startMirror();
sleep();
sleep();
sleep();
sleep();
sleep();
assertThat(readFile(new File(root2, "foo.txt")), is("abc"));
}
private void startMirror() throws Exception {
// server
int port = nextPort++; | // Path: src/test/java/mirror/TestUtils.java
// public static String readFile(final File file) throws IOException {
// return FileUtils.readFileToString(file, UTF_8);
// }
//
// Path: src/test/java/mirror/TestUtils.java
// public static void writeFile(final File file, final String data) throws IOException {
// FileUtils.writeStringToFile(file, data, UTF_8);
// }
//
// Path: src/main/java/mirror/tasks/TaskFactory.java
// public interface TaskFactory {
//
// default TaskHandle runTask(TaskLogic logic) {
// return runTask(logic, null);
// }
//
// TaskHandle runTask(TaskLogic logic, Runnable onFailure);
//
// void stopTask(TaskLogic logic);
//
// default TaskPool newTaskPool() {
// return new TaskPool(this);
// }
//
// }
//
// Path: src/main/java/mirror/tasks/ThreadBasedTaskFactory.java
// public class ThreadBasedTaskFactory implements TaskFactory {
//
// private final ConcurrentHashMap<TaskLogic, ThreadBasedTask> tasks = new ConcurrentHashMap<>();
//
// @Override
// public TaskHandle runTask(TaskLogic logic, Runnable onFailure) {
// ThreadBasedTask task = new ThreadBasedTask(logic, onFailure, () -> {
// // we don't need to call stopTask(logic) or task.stop because the task is already stopping,
// // we just to ensure we remove this entry from our map to avoid memory leaks
// tasks.remove(logic);
// });
// tasks.put(logic, task);
// task.start();
// return () -> stopTask(logic);
// }
//
// // Note that this method isn't synchronized, as while shutting down one task,
// // while we block on task.stop completing, the task might ask us to shut down
// // one of it's child tasks, but from it's own thread, which would block.
// @Override
// public void stopTask(TaskLogic logic) {
// ThreadBasedTask task = tasks.get(logic);
// if (task != null) {
// tasks.remove(logic);
// task.stop();
// }
// }
//
// }
// Path: src/test/java/mirror/BigIntegrationTest.java
import static mirror.TestUtils.readFile;
import static mirror.TestUtils.writeFile;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import java.io.File;
import java.util.ArrayList;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.grpc.Server;
import io.grpc.inprocess.InProcessChannelBuilder;
import io.grpc.inprocess.InProcessServerBuilder;
import mirror.tasks.TaskFactory;
import mirror.tasks.ThreadBasedTaskFactory;
}
if (rpc != null) {
log.info("stopping server");
rpc.shutdown();
}
rpc.shutdown();
rpc.awaitTermination();
}
@Test
public void testLotsOfFiles() throws Exception {
for (int i = 0; i < 500; i++) {
for (int j = 0; j < 100; j++) {
for (int k = 0; k < 10; k++) {
writeFile(new File(root1, "project" + i + "/dir" + j + "/file-" + k + ".txt"), "abc");
}
}
}
startMirror();
sleep();
sleep();
sleep();
sleep();
sleep();
assertThat(readFile(new File(root2, "foo.txt")), is("abc"));
}
private void startMirror() throws Exception {
// server
int port = nextPort++; | TaskFactory serverTaskFactory = new ThreadBasedTaskFactory(); |
stephenh/mirror | src/test/java/mirror/MirrorSessionTest.java | // Path: src/main/java/mirror/tasks/StubTaskFactory.java
// public class StubTaskFactory implements TaskFactory {
//
// private final Map<TaskLogic, StubTask> tasks = new ConcurrentHashMap<>();
//
// @Override
// public TaskHandle runTask(TaskLogic logic, Runnable onFailure) {
// StubTask task = new StubTask(logic, onFailure);
// tasks.put(logic, task);
// return () -> stopTask(logic);
// }
//
// @Override
// public void stopTask(TaskLogic logic) {
// StubTask task = tasks.get(logic);
// if (task != null) {
// tasks.remove(logic);
// Utils.resetIfInterrupted(() -> task.stop());
// }
// }
//
// public void tick() {
// tasks.values().forEach(t -> Utils.resetIfInterrupted(() -> t.tick()));
// }
//
// public Duration getLastDuration(TaskLogic logic) {
// return tasks.get(logic).lastDuration;
// }
// }
| import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import io.grpc.stub.StreamObserver;
import mirror.tasks.StubTaskFactory; | package mirror;
public class MirrorSessionTest {
private final Path root = Paths.get(".");
private final StubFileAccess fileAccess = new StubFileAccess();
private final List<Update> fileUpdates = new ArrayList<>();
private final FileWatcherFactory fileWatcherFactory = Mockito.mock(FileWatcherFactory.class);
private final FileWatcher fileWatcher = Mockito.mock(FileWatcher.class); | // Path: src/main/java/mirror/tasks/StubTaskFactory.java
// public class StubTaskFactory implements TaskFactory {
//
// private final Map<TaskLogic, StubTask> tasks = new ConcurrentHashMap<>();
//
// @Override
// public TaskHandle runTask(TaskLogic logic, Runnable onFailure) {
// StubTask task = new StubTask(logic, onFailure);
// tasks.put(logic, task);
// return () -> stopTask(logic);
// }
//
// @Override
// public void stopTask(TaskLogic logic) {
// StubTask task = tasks.get(logic);
// if (task != null) {
// tasks.remove(logic);
// Utils.resetIfInterrupted(() -> task.stop());
// }
// }
//
// public void tick() {
// tasks.values().forEach(t -> Utils.resetIfInterrupted(() -> t.tick()));
// }
//
// public Duration getLastDuration(TaskLogic logic) {
// return tasks.get(logic).lastDuration;
// }
// }
// Path: src/test/java/mirror/MirrorSessionTest.java
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import io.grpc.stub.StreamObserver;
import mirror.tasks.StubTaskFactory;
package mirror;
public class MirrorSessionTest {
private final Path root = Paths.get(".");
private final StubFileAccess fileAccess = new StubFileAccess();
private final List<Update> fileUpdates = new ArrayList<>();
private final FileWatcherFactory fileWatcherFactory = Mockito.mock(FileWatcherFactory.class);
private final FileWatcher fileWatcher = Mockito.mock(FileWatcher.class); | private final StubTaskFactory taskFactory = new StubTaskFactory(); |
stephenh/mirror | src/main/java/mirror/SaveToRemote.java | // Path: src/main/java/mirror/Utils.java
// public static String abbreviatePath(String path) {
// if (StringUtils.countMatches(path, '/') < 2) {
// return path;
// } else {
// return StringUtils.substringBefore(path, "/") + "/.../" + StringUtils.substringAfterLast(path, "/");
// }
// }
//
// Path: src/main/java/mirror/Utils.java
// public static String debugString(Update u) {
// return "[" + TextFormat.shortDebugString(u).replace(": ", ":") + "]";
// }
//
// Path: src/main/java/mirror/tasks/TaskLogic.java
// public interface TaskLogic {
//
// /** Run one interaction, and return how long the task wants to sleep. */
// Duration runOneLoop() throws InterruptedException;
//
// /** Called on the task thread, before we start calling {@link #runOneLoop()} in a loop. */
// default void onStart() throws InterruptedException {
// }
//
// default void onFailure() throws InterruptedException {
// }
//
// /** Called on the task thread, after we've interrupted/stopped calling {@link #runOneLoop()}. */
// default void onStop() throws InterruptedException {
// }
//
// /**
// * Called off the task thread, when we're trying to interrupt the task.
// *
// * Most threads shouldn't need this because they'll shut down
// * when we call thread.interrupt().
// */
// default void onInterrupt() {
// }
//
// default String getName() {
// String name = getClass().getSimpleName();
// // lambdas don't have simple names
// if (name.equals("")) {
// name = StringUtils.substringAfterLast(getClass().getName(), ".");
// }
// return name;
// }
// }
| import static mirror.Utils.abbreviatePath;
import static mirror.Utils.debugString;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Paths;
import java.time.Duration;
import java.util.concurrent.BlockingQueue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.annotations.VisibleForTesting;
import mirror.tasks.TaskLogic; | this.fileAccess = fileAccess;
this.results = queues.saveToRemote;
this.outgoingChanges = outgoingChanges;
}
@Override
public Duration runOneLoop() throws InterruptedException {
Update u = results.take();
try {
sendToRemote(u);
} catch (RuntimeException e) {
log.error("Exception with results " + u, e);
}
return null;
}
@VisibleForTesting
void drain() throws Exception {
while (!results.isEmpty()) {
sendToRemote(results.take());
}
}
private void sendToRemote(Update update) {
try {
Update.Builder b = Update.newBuilder(update).setLocal(false);
if (!update.getDirectory() && update.getSymlink().isEmpty() && !update.getDelete()) {
b.setData(fileAccess.read(Paths.get(update.getPath())));
}
String maybeDelete = update.getDelete() ? "(delete) " : ""; | // Path: src/main/java/mirror/Utils.java
// public static String abbreviatePath(String path) {
// if (StringUtils.countMatches(path, '/') < 2) {
// return path;
// } else {
// return StringUtils.substringBefore(path, "/") + "/.../" + StringUtils.substringAfterLast(path, "/");
// }
// }
//
// Path: src/main/java/mirror/Utils.java
// public static String debugString(Update u) {
// return "[" + TextFormat.shortDebugString(u).replace(": ", ":") + "]";
// }
//
// Path: src/main/java/mirror/tasks/TaskLogic.java
// public interface TaskLogic {
//
// /** Run one interaction, and return how long the task wants to sleep. */
// Duration runOneLoop() throws InterruptedException;
//
// /** Called on the task thread, before we start calling {@link #runOneLoop()} in a loop. */
// default void onStart() throws InterruptedException {
// }
//
// default void onFailure() throws InterruptedException {
// }
//
// /** Called on the task thread, after we've interrupted/stopped calling {@link #runOneLoop()}. */
// default void onStop() throws InterruptedException {
// }
//
// /**
// * Called off the task thread, when we're trying to interrupt the task.
// *
// * Most threads shouldn't need this because they'll shut down
// * when we call thread.interrupt().
// */
// default void onInterrupt() {
// }
//
// default String getName() {
// String name = getClass().getSimpleName();
// // lambdas don't have simple names
// if (name.equals("")) {
// name = StringUtils.substringAfterLast(getClass().getName(), ".");
// }
// return name;
// }
// }
// Path: src/main/java/mirror/SaveToRemote.java
import static mirror.Utils.abbreviatePath;
import static mirror.Utils.debugString;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Paths;
import java.time.Duration;
import java.util.concurrent.BlockingQueue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.annotations.VisibleForTesting;
import mirror.tasks.TaskLogic;
this.fileAccess = fileAccess;
this.results = queues.saveToRemote;
this.outgoingChanges = outgoingChanges;
}
@Override
public Duration runOneLoop() throws InterruptedException {
Update u = results.take();
try {
sendToRemote(u);
} catch (RuntimeException e) {
log.error("Exception with results " + u, e);
}
return null;
}
@VisibleForTesting
void drain() throws Exception {
while (!results.isEmpty()) {
sendToRemote(results.take());
}
}
private void sendToRemote(Update update) {
try {
Update.Builder b = Update.newBuilder(update).setLocal(false);
if (!update.getDirectory() && update.getSymlink().isEmpty() && !update.getDelete()) {
b.setData(fileAccess.read(Paths.get(update.getPath())));
}
String maybeDelete = update.getDelete() ? "(delete) " : ""; | log.info("Sending " + maybeDelete + abbreviatePath(update.getPath())); |
stephenh/mirror | src/main/java/mirror/SaveToRemote.java | // Path: src/main/java/mirror/Utils.java
// public static String abbreviatePath(String path) {
// if (StringUtils.countMatches(path, '/') < 2) {
// return path;
// } else {
// return StringUtils.substringBefore(path, "/") + "/.../" + StringUtils.substringAfterLast(path, "/");
// }
// }
//
// Path: src/main/java/mirror/Utils.java
// public static String debugString(Update u) {
// return "[" + TextFormat.shortDebugString(u).replace(": ", ":") + "]";
// }
//
// Path: src/main/java/mirror/tasks/TaskLogic.java
// public interface TaskLogic {
//
// /** Run one interaction, and return how long the task wants to sleep. */
// Duration runOneLoop() throws InterruptedException;
//
// /** Called on the task thread, before we start calling {@link #runOneLoop()} in a loop. */
// default void onStart() throws InterruptedException {
// }
//
// default void onFailure() throws InterruptedException {
// }
//
// /** Called on the task thread, after we've interrupted/stopped calling {@link #runOneLoop()}. */
// default void onStop() throws InterruptedException {
// }
//
// /**
// * Called off the task thread, when we're trying to interrupt the task.
// *
// * Most threads shouldn't need this because they'll shut down
// * when we call thread.interrupt().
// */
// default void onInterrupt() {
// }
//
// default String getName() {
// String name = getClass().getSimpleName();
// // lambdas don't have simple names
// if (name.equals("")) {
// name = StringUtils.substringAfterLast(getClass().getName(), ".");
// }
// return name;
// }
// }
| import static mirror.Utils.abbreviatePath;
import static mirror.Utils.debugString;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Paths;
import java.time.Duration;
import java.util.concurrent.BlockingQueue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.annotations.VisibleForTesting;
import mirror.tasks.TaskLogic; | public Duration runOneLoop() throws InterruptedException {
Update u = results.take();
try {
sendToRemote(u);
} catch (RuntimeException e) {
log.error("Exception with results " + u, e);
}
return null;
}
@VisibleForTesting
void drain() throws Exception {
while (!results.isEmpty()) {
sendToRemote(results.take());
}
}
private void sendToRemote(Update update) {
try {
Update.Builder b = Update.newBuilder(update).setLocal(false);
if (!update.getDirectory() && update.getSymlink().isEmpty() && !update.getDelete()) {
b.setData(fileAccess.read(Paths.get(update.getPath())));
}
String maybeDelete = update.getDelete() ? "(delete) " : "";
log.info("Sending " + maybeDelete + abbreviatePath(update.getPath()));
outgoingChanges.send(b.build());
} catch (FileNotFoundException e) {
// the file was very transient, which is fine, just drop it.
} catch (IOException e) {
// should we error here, so that the session is restarted? | // Path: src/main/java/mirror/Utils.java
// public static String abbreviatePath(String path) {
// if (StringUtils.countMatches(path, '/') < 2) {
// return path;
// } else {
// return StringUtils.substringBefore(path, "/") + "/.../" + StringUtils.substringAfterLast(path, "/");
// }
// }
//
// Path: src/main/java/mirror/Utils.java
// public static String debugString(Update u) {
// return "[" + TextFormat.shortDebugString(u).replace(": ", ":") + "]";
// }
//
// Path: src/main/java/mirror/tasks/TaskLogic.java
// public interface TaskLogic {
//
// /** Run one interaction, and return how long the task wants to sleep. */
// Duration runOneLoop() throws InterruptedException;
//
// /** Called on the task thread, before we start calling {@link #runOneLoop()} in a loop. */
// default void onStart() throws InterruptedException {
// }
//
// default void onFailure() throws InterruptedException {
// }
//
// /** Called on the task thread, after we've interrupted/stopped calling {@link #runOneLoop()}. */
// default void onStop() throws InterruptedException {
// }
//
// /**
// * Called off the task thread, when we're trying to interrupt the task.
// *
// * Most threads shouldn't need this because they'll shut down
// * when we call thread.interrupt().
// */
// default void onInterrupt() {
// }
//
// default String getName() {
// String name = getClass().getSimpleName();
// // lambdas don't have simple names
// if (name.equals("")) {
// name = StringUtils.substringAfterLast(getClass().getName(), ".");
// }
// return name;
// }
// }
// Path: src/main/java/mirror/SaveToRemote.java
import static mirror.Utils.abbreviatePath;
import static mirror.Utils.debugString;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Paths;
import java.time.Duration;
import java.util.concurrent.BlockingQueue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.annotations.VisibleForTesting;
import mirror.tasks.TaskLogic;
public Duration runOneLoop() throws InterruptedException {
Update u = results.take();
try {
sendToRemote(u);
} catch (RuntimeException e) {
log.error("Exception with results " + u, e);
}
return null;
}
@VisibleForTesting
void drain() throws Exception {
while (!results.isEmpty()) {
sendToRemote(results.take());
}
}
private void sendToRemote(Update update) {
try {
Update.Builder b = Update.newBuilder(update).setLocal(false);
if (!update.getDirectory() && update.getSymlink().isEmpty() && !update.getDelete()) {
b.setData(fileAccess.read(Paths.get(update.getPath())));
}
String maybeDelete = update.getDelete() ? "(delete) " : "";
log.info("Sending " + maybeDelete + abbreviatePath(update.getPath()));
outgoingChanges.send(b.build());
} catch (FileNotFoundException e) {
// the file was very transient, which is fine, just drop it.
} catch (IOException e) {
// should we error here, so that the session is restarted? | log.error("Could not read " + debugString(update), e); |
stephenh/mirror | src/test/java/mirror/watchman/WatchmanFileWatcherTest.java | // Path: src/main/java/mirror/MirrorPaths.java
// public class MirrorPaths {
//
// public final Path root;
// public final Path remoteRoot;
// private final PathRules includes;
// private final PathRules excludes;
// private final boolean debugAll;
// private final List<String> debugPrefixes;
//
// public static MirrorPaths forTesting(Path local) {
// return new MirrorPaths(local, null, new PathRules(), new PathRules(), false, new ArrayList<>());
// }
//
// public MirrorPaths(Path root, Path remoteRoot, PathRules includes, PathRules excludes, boolean debugAll, List<String> debugPrefixes) {
// this.root = root;
// this.remoteRoot = remoteRoot;
// this.includes = includes;
// this.excludes = excludes;
// this.debugAll = debugAll;
// this.debugPrefixes = debugPrefixes;
// }
//
// public void addParameters(InitialSyncRequest.Builder req) {
// req.addAllIncludes(includes.getLines());
// req.addAllExcludes(excludes.getLines());
// req.addAllDebugPrefixes(debugPrefixes);
// }
//
// public boolean isIncluded(String path, boolean directory) {
// return includes.matches(path, directory);
// }
//
// public boolean isExcluded(String path, boolean directory) {
// return excludes.matches(path, directory);
// }
//
// public boolean shouldDebug(Node node) {
// // avoid calcing the path if we have no prefixes anyway
// if (debugAll) {
// return true;
// }
// if (debugPrefixes.isEmpty()) {
// return false;
// }
// return shouldDebug(node.getPath());
// }
//
// public boolean shouldDebug(String path) {
// if (debugAll) {
// return true;
// }
// return debugPrefixes.stream().anyMatch(prefix -> path.startsWith(prefix));
// }
//
// }
| import static com.google.common.collect.Lists.newArrayList;
import static org.mockito.ArgumentMatchers.anyMap;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import com.facebook.watchman.Callback;
import com.facebook.watchman.WatchmanClient.SubscriptionDescriptor;
import com.google.common.collect.ImmutableMap;
import mirror.MirrorPaths;
import mirror.Update; | package mirror.watchman;
/**
* Tests {@link WatchmanFileWatcher}.
*/
public class WatchmanFileWatcherTest {
private final class StubDescriptor extends SubscriptionDescriptor {
@Override
public String root() {
return null;
}
@Override
public String name() {
return null;
}
}
private static final String absRoot = "/foo/bar/zaz";
private static final Path root = Paths.get(absRoot);
private Watchman wm = null;
private BlockingQueue<Update> queue = new ArrayBlockingQueue<Update>(100);
private Map<String, Object> queryParams = new HashMap<>();
@Test
public void shouldHandleWatchProjectReturningAPrefix() throws Exception {
// given we watch /foo/bar/zaz and /foo is already the watch root
setupWatchman("/foo", Optional.of("bar/zaz")); | // Path: src/main/java/mirror/MirrorPaths.java
// public class MirrorPaths {
//
// public final Path root;
// public final Path remoteRoot;
// private final PathRules includes;
// private final PathRules excludes;
// private final boolean debugAll;
// private final List<String> debugPrefixes;
//
// public static MirrorPaths forTesting(Path local) {
// return new MirrorPaths(local, null, new PathRules(), new PathRules(), false, new ArrayList<>());
// }
//
// public MirrorPaths(Path root, Path remoteRoot, PathRules includes, PathRules excludes, boolean debugAll, List<String> debugPrefixes) {
// this.root = root;
// this.remoteRoot = remoteRoot;
// this.includes = includes;
// this.excludes = excludes;
// this.debugAll = debugAll;
// this.debugPrefixes = debugPrefixes;
// }
//
// public void addParameters(InitialSyncRequest.Builder req) {
// req.addAllIncludes(includes.getLines());
// req.addAllExcludes(excludes.getLines());
// req.addAllDebugPrefixes(debugPrefixes);
// }
//
// public boolean isIncluded(String path, boolean directory) {
// return includes.matches(path, directory);
// }
//
// public boolean isExcluded(String path, boolean directory) {
// return excludes.matches(path, directory);
// }
//
// public boolean shouldDebug(Node node) {
// // avoid calcing the path if we have no prefixes anyway
// if (debugAll) {
// return true;
// }
// if (debugPrefixes.isEmpty()) {
// return false;
// }
// return shouldDebug(node.getPath());
// }
//
// public boolean shouldDebug(String path) {
// if (debugAll) {
// return true;
// }
// return debugPrefixes.stream().anyMatch(prefix -> path.startsWith(prefix));
// }
//
// }
// Path: src/test/java/mirror/watchman/WatchmanFileWatcherTest.java
import static com.google.common.collect.Lists.newArrayList;
import static org.mockito.ArgumentMatchers.anyMap;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import com.facebook.watchman.Callback;
import com.facebook.watchman.WatchmanClient.SubscriptionDescriptor;
import com.google.common.collect.ImmutableMap;
import mirror.MirrorPaths;
import mirror.Update;
package mirror.watchman;
/**
* Tests {@link WatchmanFileWatcher}.
*/
public class WatchmanFileWatcherTest {
private final class StubDescriptor extends SubscriptionDescriptor {
@Override
public String root() {
return null;
}
@Override
public String name() {
return null;
}
}
private static final String absRoot = "/foo/bar/zaz";
private static final Path root = Paths.get(absRoot);
private Watchman wm = null;
private BlockingQueue<Update> queue = new ArrayBlockingQueue<Update>(100);
private Map<String, Object> queryParams = new HashMap<>();
@Test
public void shouldHandleWatchProjectReturningAPrefix() throws Exception {
// given we watch /foo/bar/zaz and /foo is already the watch root
setupWatchman("/foo", Optional.of("bar/zaz")); | WatchmanFileWatcher fw = new WatchmanFileWatcher(wm, MirrorPaths.forTesting(root), queue); |
stephenh/mirror | src/main/java/mirror/tasks/ThreadBasedTask.java | // Path: src/main/java/mirror/Utils.java
// public class Utils {
//
// private static final Logger log = LoggerFactory.getLogger(Utils.class);
//
// @FunctionalInterface
// public interface InterruptedRunnable {
// void run() throws InterruptedException;
// }
//
// /** grpc-java doesn't support timeouts yet, so we have to set a per-call deadline. */
// public static MirrorStub withTimeout(MirrorStub s) {
// // over VPN, ~100k files can take 30 seconds.
// return s.withDeadlineAfter(10, TimeUnit.MINUTES);
// }
//
// public static void logConnectionError(Logger log, Throwable t) {
// if (t instanceof StatusRuntimeException) {
// log.info("Connection status: " + niceToString(((StatusRuntimeException) t).getStatus()));
// } else if (t instanceof StatusException) {
// log.info("Connection status: " + niceToString(((StatusException) t).getStatus()));
// } else {
// log.error("Error from stream: " + t.getMessage(), t);
// }
// }
//
// private static String niceToString(Status status) {
// // the default Status.toString has a stack trace in it, which is ugly
// return MoreObjects
// .toStringHelper(status)
// .add("code", status.getCode().name())
// .add("description", status.getDescription())
// .add("cause", status.getCause() != null ? status.getCause().getMessage() : null)
// .toString();
// }
//
// public static void resetIfInterrupted(InterruptedRunnable r) {
// try {
// r.run();
// } catch (InterruptedException e) {
// Thread.currentThread().interrupt();
// throw new RuntimeException(e);
// }
// }
//
// public static String debugString(Update u) {
// return "[" + TextFormat.shortDebugString(u).replace(": ", ":") + "]";
// }
//
// public static void time(Logger log, String action, Runnable r) {
// log.info("Starting " + action);
// long start = System.currentTimeMillis();
// r.run();
// long stop = System.currentTimeMillis();
// log.info("Completed " + action + ": " + (stop - start) + "ms");
// }
//
// /** Waits until {@code path} is not longer being actively written to (best-effort). */
// public static void ensureSettled(FileAccess fileAccess, Path path) throws InterruptedException {
// // do some gyrations to ensure the file writer has completely written the file
// boolean shouldBeComplete = false;
// try {
// while (!shouldBeComplete) {
// long localModTime = fileAccess.getModifiedTime(path);
// if (fileWasJustModified(localModTime)) {
// long size1 = fileAccess.getFileSize(path);
// Thread.sleep(500); // 100ms was too small
// long size2 = fileAccess.getFileSize(path);
// shouldBeComplete = size1 == size2;
// if (!shouldBeComplete) {
// log.debug("{} not settled {} {}", path, size1, size2);
// }
// } else {
// shouldBeComplete = true; // no need to check
// }
// }
// } catch (IOException io) {
// // assume the file disappeared, and we'll catch it later
// return;
// }
// }
//
// /** @return whether localModTime was within the last 2 seconds. */
// private static boolean fileWasJustModified(long localModTime) {
// return (System.currentTimeMillis() - localModTime) <= 2000;
// }
//
// public static String abbreviatePath(String path) {
// if (StringUtils.countMatches(path, '/') < 2) {
// return path;
// } else {
// return StringUtils.substringBefore(path, "/") + "/.../" + StringUtils.substringAfterLast(path, "/");
// }
// }
//
// }
| import java.time.Duration;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import mirror.Utils; | package mirror.tasks;
/**
* Provides some basic "start up a thread and poll a queue" abstractions.
*
* Kind of actor-like. Ish.
*/
class ThreadBasedTask {
private static int nextThread = 0;
protected final Logger log = LoggerFactory.getLogger(getClass());
private final AtomicBoolean shutdown = new AtomicBoolean(false);
private final CountDownLatch isStarted = new CountDownLatch(1);
private final CountDownLatch isShutdown = new CountDownLatch(1);
private final Thread thread;
private final TaskLogic task;
private final Runnable onFailure;
private final Runnable onStop;
private static synchronized int nextThreadId() {
return nextThread++;
}
protected ThreadBasedTask(TaskLogic task, Runnable onFailure, Runnable onStop) {
this.task = task;
this.onFailure = onFailure;
this.onStop = onStop;
thread = new ThreadFactoryBuilder().setDaemon(true).setNameFormat(nextThreadId() + "-" + task.getName() + "-%s").build().newThread(() -> run());
}
void start() {
thread.start(); | // Path: src/main/java/mirror/Utils.java
// public class Utils {
//
// private static final Logger log = LoggerFactory.getLogger(Utils.class);
//
// @FunctionalInterface
// public interface InterruptedRunnable {
// void run() throws InterruptedException;
// }
//
// /** grpc-java doesn't support timeouts yet, so we have to set a per-call deadline. */
// public static MirrorStub withTimeout(MirrorStub s) {
// // over VPN, ~100k files can take 30 seconds.
// return s.withDeadlineAfter(10, TimeUnit.MINUTES);
// }
//
// public static void logConnectionError(Logger log, Throwable t) {
// if (t instanceof StatusRuntimeException) {
// log.info("Connection status: " + niceToString(((StatusRuntimeException) t).getStatus()));
// } else if (t instanceof StatusException) {
// log.info("Connection status: " + niceToString(((StatusException) t).getStatus()));
// } else {
// log.error("Error from stream: " + t.getMessage(), t);
// }
// }
//
// private static String niceToString(Status status) {
// // the default Status.toString has a stack trace in it, which is ugly
// return MoreObjects
// .toStringHelper(status)
// .add("code", status.getCode().name())
// .add("description", status.getDescription())
// .add("cause", status.getCause() != null ? status.getCause().getMessage() : null)
// .toString();
// }
//
// public static void resetIfInterrupted(InterruptedRunnable r) {
// try {
// r.run();
// } catch (InterruptedException e) {
// Thread.currentThread().interrupt();
// throw new RuntimeException(e);
// }
// }
//
// public static String debugString(Update u) {
// return "[" + TextFormat.shortDebugString(u).replace(": ", ":") + "]";
// }
//
// public static void time(Logger log, String action, Runnable r) {
// log.info("Starting " + action);
// long start = System.currentTimeMillis();
// r.run();
// long stop = System.currentTimeMillis();
// log.info("Completed " + action + ": " + (stop - start) + "ms");
// }
//
// /** Waits until {@code path} is not longer being actively written to (best-effort). */
// public static void ensureSettled(FileAccess fileAccess, Path path) throws InterruptedException {
// // do some gyrations to ensure the file writer has completely written the file
// boolean shouldBeComplete = false;
// try {
// while (!shouldBeComplete) {
// long localModTime = fileAccess.getModifiedTime(path);
// if (fileWasJustModified(localModTime)) {
// long size1 = fileAccess.getFileSize(path);
// Thread.sleep(500); // 100ms was too small
// long size2 = fileAccess.getFileSize(path);
// shouldBeComplete = size1 == size2;
// if (!shouldBeComplete) {
// log.debug("{} not settled {} {}", path, size1, size2);
// }
// } else {
// shouldBeComplete = true; // no need to check
// }
// }
// } catch (IOException io) {
// // assume the file disappeared, and we'll catch it later
// return;
// }
// }
//
// /** @return whether localModTime was within the last 2 seconds. */
// private static boolean fileWasJustModified(long localModTime) {
// return (System.currentTimeMillis() - localModTime) <= 2000;
// }
//
// public static String abbreviatePath(String path) {
// if (StringUtils.countMatches(path, '/') < 2) {
// return path;
// } else {
// return StringUtils.substringBefore(path, "/") + "/.../" + StringUtils.substringAfterLast(path, "/");
// }
// }
//
// }
// Path: src/main/java/mirror/tasks/ThreadBasedTask.java
import java.time.Duration;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import mirror.Utils;
package mirror.tasks;
/**
* Provides some basic "start up a thread and poll a queue" abstractions.
*
* Kind of actor-like. Ish.
*/
class ThreadBasedTask {
private static int nextThread = 0;
protected final Logger log = LoggerFactory.getLogger(getClass());
private final AtomicBoolean shutdown = new AtomicBoolean(false);
private final CountDownLatch isStarted = new CountDownLatch(1);
private final CountDownLatch isShutdown = new CountDownLatch(1);
private final Thread thread;
private final TaskLogic task;
private final Runnable onFailure;
private final Runnable onStop;
private static synchronized int nextThreadId() {
return nextThread++;
}
protected ThreadBasedTask(TaskLogic task, Runnable onFailure, Runnable onStop) {
this.task = task;
this.onFailure = onFailure;
this.onStop = onStop;
thread = new ThreadFactoryBuilder().setDaemon(true).setNameFormat(nextThreadId() + "-" + task.getName() + "-%s").build().newThread(() -> run());
}
void start() {
thread.start(); | Utils.resetIfInterrupted(() -> isStarted.await()); |
stephenh/mirror | src/main/java/mirror/MirrorServer.java | // Path: src/main/java/mirror/tasks/TaskFactory.java
// public interface TaskFactory {
//
// default TaskHandle runTask(TaskLogic logic) {
// return runTask(logic, null);
// }
//
// TaskHandle runTask(TaskLogic logic, Runnable onFailure);
//
// void stopTask(TaskLogic logic);
//
// default TaskPool newTaskPool() {
// return new TaskPool(this);
// }
//
// }
| import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.annotations.VisibleForTesting;
import io.grpc.Metadata;
import io.grpc.ServerCall;
import io.grpc.ServerCall.Listener;
import io.grpc.ServerCallHandler;
import io.grpc.ServerInterceptor;
import io.grpc.stub.CallStreamObserver;
import io.grpc.stub.StreamObserver;
import mirror.MirrorGrpc.MirrorImplBase;
import mirror.tasks.TaskFactory; | package mirror;
/**
* Listens for incoming clients and sets up {@link MirrorSession}s.
*
* In theory we can juggle multiple sessions, potentially even to the same destination
* path, and things should just work (the sessions won't communicate directly, but instead
* will see each other's file writes just like any other writer).
*/
public class MirrorServer extends MirrorImplBase {
/**
* Currently grpc-java doesn't return compressed responses, even if the client
* has sent a compressed payload. This turns on gzip compression for all responses.
*/
public static class EnableCompressionInterceptor implements ServerInterceptor {
@Override
public <ReqT, RespT> Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) {
call.setCompression("gzip");
return next.startCall(call, headers);
}
}
private static final Logger log = LoggerFactory.getLogger(MirrorServer.class);
private final Map<String, MirrorSession> sessions = new HashMap<>(); | // Path: src/main/java/mirror/tasks/TaskFactory.java
// public interface TaskFactory {
//
// default TaskHandle runTask(TaskLogic logic) {
// return runTask(logic, null);
// }
//
// TaskHandle runTask(TaskLogic logic, Runnable onFailure);
//
// void stopTask(TaskLogic logic);
//
// default TaskPool newTaskPool() {
// return new TaskPool(this);
// }
//
// }
// Path: src/main/java/mirror/MirrorServer.java
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.annotations.VisibleForTesting;
import io.grpc.Metadata;
import io.grpc.ServerCall;
import io.grpc.ServerCall.Listener;
import io.grpc.ServerCallHandler;
import io.grpc.ServerInterceptor;
import io.grpc.stub.CallStreamObserver;
import io.grpc.stub.StreamObserver;
import mirror.MirrorGrpc.MirrorImplBase;
import mirror.tasks.TaskFactory;
package mirror;
/**
* Listens for incoming clients and sets up {@link MirrorSession}s.
*
* In theory we can juggle multiple sessions, potentially even to the same destination
* path, and things should just work (the sessions won't communicate directly, but instead
* will see each other's file writes just like any other writer).
*/
public class MirrorServer extends MirrorImplBase {
/**
* Currently grpc-java doesn't return compressed responses, even if the client
* has sent a compressed payload. This turns on gzip compression for all responses.
*/
public static class EnableCompressionInterceptor implements ServerInterceptor {
@Override
public <ReqT, RespT> Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) {
call.setCompression("gzip");
return next.startCall(call, headers);
}
}
private static final Logger log = LoggerFactory.getLogger(MirrorServer.class);
private final Map<String, MirrorSession> sessions = new HashMap<>(); | private final TaskFactory taskFactory; |
stephenh/mirror | src/main/java/mirror/tasks/StubTaskFactory.java | // Path: src/main/java/mirror/Utils.java
// public class Utils {
//
// private static final Logger log = LoggerFactory.getLogger(Utils.class);
//
// @FunctionalInterface
// public interface InterruptedRunnable {
// void run() throws InterruptedException;
// }
//
// /** grpc-java doesn't support timeouts yet, so we have to set a per-call deadline. */
// public static MirrorStub withTimeout(MirrorStub s) {
// // over VPN, ~100k files can take 30 seconds.
// return s.withDeadlineAfter(10, TimeUnit.MINUTES);
// }
//
// public static void logConnectionError(Logger log, Throwable t) {
// if (t instanceof StatusRuntimeException) {
// log.info("Connection status: " + niceToString(((StatusRuntimeException) t).getStatus()));
// } else if (t instanceof StatusException) {
// log.info("Connection status: " + niceToString(((StatusException) t).getStatus()));
// } else {
// log.error("Error from stream: " + t.getMessage(), t);
// }
// }
//
// private static String niceToString(Status status) {
// // the default Status.toString has a stack trace in it, which is ugly
// return MoreObjects
// .toStringHelper(status)
// .add("code", status.getCode().name())
// .add("description", status.getDescription())
// .add("cause", status.getCause() != null ? status.getCause().getMessage() : null)
// .toString();
// }
//
// public static void resetIfInterrupted(InterruptedRunnable r) {
// try {
// r.run();
// } catch (InterruptedException e) {
// Thread.currentThread().interrupt();
// throw new RuntimeException(e);
// }
// }
//
// public static String debugString(Update u) {
// return "[" + TextFormat.shortDebugString(u).replace(": ", ":") + "]";
// }
//
// public static void time(Logger log, String action, Runnable r) {
// log.info("Starting " + action);
// long start = System.currentTimeMillis();
// r.run();
// long stop = System.currentTimeMillis();
// log.info("Completed " + action + ": " + (stop - start) + "ms");
// }
//
// /** Waits until {@code path} is not longer being actively written to (best-effort). */
// public static void ensureSettled(FileAccess fileAccess, Path path) throws InterruptedException {
// // do some gyrations to ensure the file writer has completely written the file
// boolean shouldBeComplete = false;
// try {
// while (!shouldBeComplete) {
// long localModTime = fileAccess.getModifiedTime(path);
// if (fileWasJustModified(localModTime)) {
// long size1 = fileAccess.getFileSize(path);
// Thread.sleep(500); // 100ms was too small
// long size2 = fileAccess.getFileSize(path);
// shouldBeComplete = size1 == size2;
// if (!shouldBeComplete) {
// log.debug("{} not settled {} {}", path, size1, size2);
// }
// } else {
// shouldBeComplete = true; // no need to check
// }
// }
// } catch (IOException io) {
// // assume the file disappeared, and we'll catch it later
// return;
// }
// }
//
// /** @return whether localModTime was within the last 2 seconds. */
// private static boolean fileWasJustModified(long localModTime) {
// return (System.currentTimeMillis() - localModTime) <= 2000;
// }
//
// public static String abbreviatePath(String path) {
// if (StringUtils.countMatches(path, '/') < 2) {
// return path;
// } else {
// return StringUtils.substringBefore(path, "/") + "/.../" + StringUtils.substringAfterLast(path, "/");
// }
// }
//
// }
| import java.time.Duration;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import mirror.Utils; | package mirror.tasks;
public class StubTaskFactory implements TaskFactory {
private final Map<TaskLogic, StubTask> tasks = new ConcurrentHashMap<>();
@Override
public TaskHandle runTask(TaskLogic logic, Runnable onFailure) {
StubTask task = new StubTask(logic, onFailure);
tasks.put(logic, task);
return () -> stopTask(logic);
}
@Override
public void stopTask(TaskLogic logic) {
StubTask task = tasks.get(logic);
if (task != null) {
tasks.remove(logic); | // Path: src/main/java/mirror/Utils.java
// public class Utils {
//
// private static final Logger log = LoggerFactory.getLogger(Utils.class);
//
// @FunctionalInterface
// public interface InterruptedRunnable {
// void run() throws InterruptedException;
// }
//
// /** grpc-java doesn't support timeouts yet, so we have to set a per-call deadline. */
// public static MirrorStub withTimeout(MirrorStub s) {
// // over VPN, ~100k files can take 30 seconds.
// return s.withDeadlineAfter(10, TimeUnit.MINUTES);
// }
//
// public static void logConnectionError(Logger log, Throwable t) {
// if (t instanceof StatusRuntimeException) {
// log.info("Connection status: " + niceToString(((StatusRuntimeException) t).getStatus()));
// } else if (t instanceof StatusException) {
// log.info("Connection status: " + niceToString(((StatusException) t).getStatus()));
// } else {
// log.error("Error from stream: " + t.getMessage(), t);
// }
// }
//
// private static String niceToString(Status status) {
// // the default Status.toString has a stack trace in it, which is ugly
// return MoreObjects
// .toStringHelper(status)
// .add("code", status.getCode().name())
// .add("description", status.getDescription())
// .add("cause", status.getCause() != null ? status.getCause().getMessage() : null)
// .toString();
// }
//
// public static void resetIfInterrupted(InterruptedRunnable r) {
// try {
// r.run();
// } catch (InterruptedException e) {
// Thread.currentThread().interrupt();
// throw new RuntimeException(e);
// }
// }
//
// public static String debugString(Update u) {
// return "[" + TextFormat.shortDebugString(u).replace(": ", ":") + "]";
// }
//
// public static void time(Logger log, String action, Runnable r) {
// log.info("Starting " + action);
// long start = System.currentTimeMillis();
// r.run();
// long stop = System.currentTimeMillis();
// log.info("Completed " + action + ": " + (stop - start) + "ms");
// }
//
// /** Waits until {@code path} is not longer being actively written to (best-effort). */
// public static void ensureSettled(FileAccess fileAccess, Path path) throws InterruptedException {
// // do some gyrations to ensure the file writer has completely written the file
// boolean shouldBeComplete = false;
// try {
// while (!shouldBeComplete) {
// long localModTime = fileAccess.getModifiedTime(path);
// if (fileWasJustModified(localModTime)) {
// long size1 = fileAccess.getFileSize(path);
// Thread.sleep(500); // 100ms was too small
// long size2 = fileAccess.getFileSize(path);
// shouldBeComplete = size1 == size2;
// if (!shouldBeComplete) {
// log.debug("{} not settled {} {}", path, size1, size2);
// }
// } else {
// shouldBeComplete = true; // no need to check
// }
// }
// } catch (IOException io) {
// // assume the file disappeared, and we'll catch it later
// return;
// }
// }
//
// /** @return whether localModTime was within the last 2 seconds. */
// private static boolean fileWasJustModified(long localModTime) {
// return (System.currentTimeMillis() - localModTime) <= 2000;
// }
//
// public static String abbreviatePath(String path) {
// if (StringUtils.countMatches(path, '/') < 2) {
// return path;
// } else {
// return StringUtils.substringBefore(path, "/") + "/.../" + StringUtils.substringAfterLast(path, "/");
// }
// }
//
// }
// Path: src/main/java/mirror/tasks/StubTaskFactory.java
import java.time.Duration;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import mirror.Utils;
package mirror.tasks;
public class StubTaskFactory implements TaskFactory {
private final Map<TaskLogic, StubTask> tasks = new ConcurrentHashMap<>();
@Override
public TaskHandle runTask(TaskLogic logic, Runnable onFailure) {
StubTask task = new StubTask(logic, onFailure);
tasks.put(logic, task);
return () -> stopTask(logic);
}
@Override
public void stopTask(TaskLogic logic) {
StubTask task = tasks.get(logic);
if (task != null) {
tasks.remove(logic); | Utils.resetIfInterrupted(() -> task.stop()); |
stephenh/mirror | src/test/java/mirror/MirrorServerTest.java | // Path: src/main/java/mirror/tasks/StubTaskFactory.java
// public class StubTaskFactory implements TaskFactory {
//
// private final Map<TaskLogic, StubTask> tasks = new ConcurrentHashMap<>();
//
// @Override
// public TaskHandle runTask(TaskLogic logic, Runnable onFailure) {
// StubTask task = new StubTask(logic, onFailure);
// tasks.put(logic, task);
// return () -> stopTask(logic);
// }
//
// @Override
// public void stopTask(TaskLogic logic) {
// StubTask task = tasks.get(logic);
// if (task != null) {
// tasks.remove(logic);
// Utils.resetIfInterrupted(() -> task.stop());
// }
// }
//
// public void tick() {
// tasks.values().forEach(t -> Utils.resetIfInterrupted(() -> t.tick()));
// }
//
// public Duration getLastDuration(TaskLogic logic) {
// return tasks.get(logic).lastDuration;
// }
// }
| import static org.hamcrest.CoreMatchers.hasItems;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import mirror.tasks.StubTaskFactory; | package mirror;
public class MirrorServerTest {
private final List<Update> fileUpdates = new ArrayList<>();
private final FileWatcherFactory fileWatcherFactory = Mockito.mock(FileWatcherFactory.class);
private final FileWatcher fileWatcher = Mockito.mock(FileWatcher.class);
private final StubFileAccess rootFileAccess = new StubFileAccess();
private final StubFileAccess sessionFileAccess = new StubFileAccess();
private final FileAccessFactory accessFactory = (path) -> sessionFileAccess; | // Path: src/main/java/mirror/tasks/StubTaskFactory.java
// public class StubTaskFactory implements TaskFactory {
//
// private final Map<TaskLogic, StubTask> tasks = new ConcurrentHashMap<>();
//
// @Override
// public TaskHandle runTask(TaskLogic logic, Runnable onFailure) {
// StubTask task = new StubTask(logic, onFailure);
// tasks.put(logic, task);
// return () -> stopTask(logic);
// }
//
// @Override
// public void stopTask(TaskLogic logic) {
// StubTask task = tasks.get(logic);
// if (task != null) {
// tasks.remove(logic);
// Utils.resetIfInterrupted(() -> task.stop());
// }
// }
//
// public void tick() {
// tasks.values().forEach(t -> Utils.resetIfInterrupted(() -> t.tick()));
// }
//
// public Duration getLastDuration(TaskLogic logic) {
// return tasks.get(logic).lastDuration;
// }
// }
// Path: src/test/java/mirror/MirrorServerTest.java
import static org.hamcrest.CoreMatchers.hasItems;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import mirror.tasks.StubTaskFactory;
package mirror;
public class MirrorServerTest {
private final List<Update> fileUpdates = new ArrayList<>();
private final FileWatcherFactory fileWatcherFactory = Mockito.mock(FileWatcherFactory.class);
private final FileWatcher fileWatcher = Mockito.mock(FileWatcher.class);
private final StubFileAccess rootFileAccess = new StubFileAccess();
private final StubFileAccess sessionFileAccess = new StubFileAccess();
private final FileAccessFactory accessFactory = (path) -> sessionFileAccess; | private final StubTaskFactory taskFactory = new StubTaskFactory(); |
stephenh/mirror | src/test/java/mirror/misc/DigestTest.java | // Path: src/main/java/mirror/misc/Digest.java
// public class Digest {
//
// public static void main(String[] args) throws Exception {
// Path root = Paths.get("/home/stephen/linkedin");
// TaskFactory taskFactory = new ThreadBasedTaskFactory();
// BlockingQueue<Update> queue = new ArrayBlockingQueue<>(1_000_000);
// WatchService watchService = FileSystems.getDefault().newWatchService();
// final Stopwatch s = Stopwatch.createStarted();
// FileWatcher r = new WatchServiceFileWatcher(taskFactory, watchService, root, queue);
// List<Update> initial = r.performInitialScan();
// s.stop();
//
// System.out.println("scan took " + s.elapsed(TimeUnit.MILLISECONDS) + " millis");
// s.reset();
// s.start();
//
// StringBuilder b = new StringBuilder();
// for (Update update : initial) {
// Path p = root.resolve(update.getPath());
// if (Files.exists(p) && Files.isRegularFile(p)) {
// b.append(getHash(p));
// }
// }
// s.stop();
//
// System.out.println("hash took " + s.elapsed(TimeUnit.MILLISECONDS) + " millis");
// }
//
// public static String getHash(Path path) throws IOException {
// try (FileChannel fc = FileChannel.open(path, StandardOpenOption.READ)) {
// MessageDigest md = MessageDigest.getInstance("MD5");
// // via naive trial/error, 1024 is better than larger values like 2048 or 8192
// ByteBuffer bbf = ByteBuffer.allocateDirect(1024);
// int b = fc.read(bbf);
// while ((b != -1) && (b != 0)) {
// bbf.flip();
// md.update(bbf);
// b = fc.read(bbf);
// }
// fc.close();
// return toHex(md.digest());
// } catch (NoSuchAlgorithmException e) {
// throw new RuntimeException(e);
// }
// }
//
// private static String toHex(byte[] bytes) {
// StringBuilder sb = new StringBuilder(bytes.length);
// for (int i = 0; i < bytes.length; i++) {
// sb.append(Integer.toHexString(0xFF & bytes[i]));
// }
// return sb.toString();
// }
//
// }
| import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import java.nio.file.Paths;
import org.junit.Test;
import mirror.misc.Digest; | package mirror.misc;
public class DigestTest {
@Test
public void testFirstImplementation() throws Exception { | // Path: src/main/java/mirror/misc/Digest.java
// public class Digest {
//
// public static void main(String[] args) throws Exception {
// Path root = Paths.get("/home/stephen/linkedin");
// TaskFactory taskFactory = new ThreadBasedTaskFactory();
// BlockingQueue<Update> queue = new ArrayBlockingQueue<>(1_000_000);
// WatchService watchService = FileSystems.getDefault().newWatchService();
// final Stopwatch s = Stopwatch.createStarted();
// FileWatcher r = new WatchServiceFileWatcher(taskFactory, watchService, root, queue);
// List<Update> initial = r.performInitialScan();
// s.stop();
//
// System.out.println("scan took " + s.elapsed(TimeUnit.MILLISECONDS) + " millis");
// s.reset();
// s.start();
//
// StringBuilder b = new StringBuilder();
// for (Update update : initial) {
// Path p = root.resolve(update.getPath());
// if (Files.exists(p) && Files.isRegularFile(p)) {
// b.append(getHash(p));
// }
// }
// s.stop();
//
// System.out.println("hash took " + s.elapsed(TimeUnit.MILLISECONDS) + " millis");
// }
//
// public static String getHash(Path path) throws IOException {
// try (FileChannel fc = FileChannel.open(path, StandardOpenOption.READ)) {
// MessageDigest md = MessageDigest.getInstance("MD5");
// // via naive trial/error, 1024 is better than larger values like 2048 or 8192
// ByteBuffer bbf = ByteBuffer.allocateDirect(1024);
// int b = fc.read(bbf);
// while ((b != -1) && (b != 0)) {
// bbf.flip();
// md.update(bbf);
// b = fc.read(bbf);
// }
// fc.close();
// return toHex(md.digest());
// } catch (NoSuchAlgorithmException e) {
// throw new RuntimeException(e);
// }
// }
//
// private static String toHex(byte[] bytes) {
// StringBuilder sb = new StringBuilder(bytes.length);
// for (int i = 0; i < bytes.length; i++) {
// sb.append(Integer.toHexString(0xFF & bytes[i]));
// }
// return sb.toString();
// }
//
// }
// Path: src/test/java/mirror/misc/DigestTest.java
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import java.nio.file.Paths;
import org.junit.Test;
import mirror.misc.Digest;
package mirror.misc;
public class DigestTest {
@Test
public void testFirstImplementation() throws Exception { | assertThat(Digest.getHash(Paths.get("./src/test/resources/bar.txt")), is("c157a79031e1c4f85931829bc5fc552")); |
stephenh/mirror | src/test/java/mirror/IntegrationTest.java | // Path: src/test/java/mirror/TestUtils.java
// public static void move(final String from, final String to) {
// new Execute(new String[] { "mv", from, to }).toSystemOut();
// }
//
// Path: src/test/java/mirror/TestUtils.java
// public static String readFile(final File file) throws IOException {
// return FileUtils.readFileToString(file, UTF_8);
// }
//
// Path: src/test/java/mirror/TestUtils.java
// public static void writeFile(final File file, final String data) throws IOException {
// FileUtils.writeStringToFile(file, data, UTF_8);
// }
//
// Path: src/main/java/mirror/tasks/TaskFactory.java
// public interface TaskFactory {
//
// default TaskHandle runTask(TaskLogic logic) {
// return runTask(logic, null);
// }
//
// TaskHandle runTask(TaskLogic logic, Runnable onFailure);
//
// void stopTask(TaskLogic logic);
//
// default TaskPool newTaskPool() {
// return new TaskPool(this);
// }
//
// }
//
// Path: src/main/java/mirror/tasks/ThreadBasedTaskFactory.java
// public class ThreadBasedTaskFactory implements TaskFactory {
//
// private final ConcurrentHashMap<TaskLogic, ThreadBasedTask> tasks = new ConcurrentHashMap<>();
//
// @Override
// public TaskHandle runTask(TaskLogic logic, Runnable onFailure) {
// ThreadBasedTask task = new ThreadBasedTask(logic, onFailure, () -> {
// // we don't need to call stopTask(logic) or task.stop because the task is already stopping,
// // we just to ensure we remove this entry from our map to avoid memory leaks
// tasks.remove(logic);
// });
// tasks.put(logic, task);
// task.start();
// return () -> stopTask(logic);
// }
//
// // Note that this method isn't synchronized, as while shutting down one task,
// // while we block on task.stop completing, the task might ask us to shut down
// // one of it's child tasks, but from it's own thread, which would block.
// @Override
// public void stopTask(TaskLogic logic) {
// ThreadBasedTask task = tasks.get(logic);
// if (task != null) {
// tasks.remove(logic);
// task.stop();
// }
// }
//
// }
| import static mirror.TestUtils.move;
import static mirror.TestUtils.readFile;
import static mirror.TestUtils.writeFile;
import static org.apache.commons.io.FileUtils.deleteDirectory;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.grpc.Server;
import io.grpc.inprocess.InProcessChannelBuilder;
import io.grpc.inprocess.InProcessServerBuilder;
import mirror.tasks.TaskFactory;
import mirror.tasks.ThreadBasedTaskFactory; | private MirrorClient client;
@Before
public void clearFiles() throws Exception {
deleteDirectory(integrationTestDir);
integrationTestDir.mkdirs();
root1.mkdirs();
root2.mkdirs();
// FileUtils.touch(new File(root1, ".watchmanconfig"));
// FileUtils.touch(new File(root2, ".watchmanconfig"));
}
@After
public void shutdown() throws Exception {
// rpc.awaitTermination();
if (client != null) {
log.info("stopping client");
client.stop();
}
if (rpc != null) {
log.info("stopping server");
rpc.shutdown();
}
rpc.shutdown();
rpc.awaitTermination();
}
@Test
public void testSimpleFile() throws Exception {
startMirror(); | // Path: src/test/java/mirror/TestUtils.java
// public static void move(final String from, final String to) {
// new Execute(new String[] { "mv", from, to }).toSystemOut();
// }
//
// Path: src/test/java/mirror/TestUtils.java
// public static String readFile(final File file) throws IOException {
// return FileUtils.readFileToString(file, UTF_8);
// }
//
// Path: src/test/java/mirror/TestUtils.java
// public static void writeFile(final File file, final String data) throws IOException {
// FileUtils.writeStringToFile(file, data, UTF_8);
// }
//
// Path: src/main/java/mirror/tasks/TaskFactory.java
// public interface TaskFactory {
//
// default TaskHandle runTask(TaskLogic logic) {
// return runTask(logic, null);
// }
//
// TaskHandle runTask(TaskLogic logic, Runnable onFailure);
//
// void stopTask(TaskLogic logic);
//
// default TaskPool newTaskPool() {
// return new TaskPool(this);
// }
//
// }
//
// Path: src/main/java/mirror/tasks/ThreadBasedTaskFactory.java
// public class ThreadBasedTaskFactory implements TaskFactory {
//
// private final ConcurrentHashMap<TaskLogic, ThreadBasedTask> tasks = new ConcurrentHashMap<>();
//
// @Override
// public TaskHandle runTask(TaskLogic logic, Runnable onFailure) {
// ThreadBasedTask task = new ThreadBasedTask(logic, onFailure, () -> {
// // we don't need to call stopTask(logic) or task.stop because the task is already stopping,
// // we just to ensure we remove this entry from our map to avoid memory leaks
// tasks.remove(logic);
// });
// tasks.put(logic, task);
// task.start();
// return () -> stopTask(logic);
// }
//
// // Note that this method isn't synchronized, as while shutting down one task,
// // while we block on task.stop completing, the task might ask us to shut down
// // one of it's child tasks, but from it's own thread, which would block.
// @Override
// public void stopTask(TaskLogic logic) {
// ThreadBasedTask task = tasks.get(logic);
// if (task != null) {
// tasks.remove(logic);
// task.stop();
// }
// }
//
// }
// Path: src/test/java/mirror/IntegrationTest.java
import static mirror.TestUtils.move;
import static mirror.TestUtils.readFile;
import static mirror.TestUtils.writeFile;
import static org.apache.commons.io.FileUtils.deleteDirectory;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.grpc.Server;
import io.grpc.inprocess.InProcessChannelBuilder;
import io.grpc.inprocess.InProcessServerBuilder;
import mirror.tasks.TaskFactory;
import mirror.tasks.ThreadBasedTaskFactory;
private MirrorClient client;
@Before
public void clearFiles() throws Exception {
deleteDirectory(integrationTestDir);
integrationTestDir.mkdirs();
root1.mkdirs();
root2.mkdirs();
// FileUtils.touch(new File(root1, ".watchmanconfig"));
// FileUtils.touch(new File(root2, ".watchmanconfig"));
}
@After
public void shutdown() throws Exception {
// rpc.awaitTermination();
if (client != null) {
log.info("stopping client");
client.stop();
}
if (rpc != null) {
log.info("stopping server");
rpc.shutdown();
}
rpc.shutdown();
rpc.awaitTermination();
}
@Test
public void testSimpleFile() throws Exception {
startMirror(); | writeFile(new File(root1, "foo.txt"), "abc"); |
stephenh/mirror | src/test/java/mirror/IntegrationTest.java | // Path: src/test/java/mirror/TestUtils.java
// public static void move(final String from, final String to) {
// new Execute(new String[] { "mv", from, to }).toSystemOut();
// }
//
// Path: src/test/java/mirror/TestUtils.java
// public static String readFile(final File file) throws IOException {
// return FileUtils.readFileToString(file, UTF_8);
// }
//
// Path: src/test/java/mirror/TestUtils.java
// public static void writeFile(final File file, final String data) throws IOException {
// FileUtils.writeStringToFile(file, data, UTF_8);
// }
//
// Path: src/main/java/mirror/tasks/TaskFactory.java
// public interface TaskFactory {
//
// default TaskHandle runTask(TaskLogic logic) {
// return runTask(logic, null);
// }
//
// TaskHandle runTask(TaskLogic logic, Runnable onFailure);
//
// void stopTask(TaskLogic logic);
//
// default TaskPool newTaskPool() {
// return new TaskPool(this);
// }
//
// }
//
// Path: src/main/java/mirror/tasks/ThreadBasedTaskFactory.java
// public class ThreadBasedTaskFactory implements TaskFactory {
//
// private final ConcurrentHashMap<TaskLogic, ThreadBasedTask> tasks = new ConcurrentHashMap<>();
//
// @Override
// public TaskHandle runTask(TaskLogic logic, Runnable onFailure) {
// ThreadBasedTask task = new ThreadBasedTask(logic, onFailure, () -> {
// // we don't need to call stopTask(logic) or task.stop because the task is already stopping,
// // we just to ensure we remove this entry from our map to avoid memory leaks
// tasks.remove(logic);
// });
// tasks.put(logic, task);
// task.start();
// return () -> stopTask(logic);
// }
//
// // Note that this method isn't synchronized, as while shutting down one task,
// // while we block on task.stop completing, the task might ask us to shut down
// // one of it's child tasks, but from it's own thread, which would block.
// @Override
// public void stopTask(TaskLogic logic) {
// ThreadBasedTask task = tasks.get(logic);
// if (task != null) {
// tasks.remove(logic);
// task.stop();
// }
// }
//
// }
| import static mirror.TestUtils.move;
import static mirror.TestUtils.readFile;
import static mirror.TestUtils.writeFile;
import static org.apache.commons.io.FileUtils.deleteDirectory;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.grpc.Server;
import io.grpc.inprocess.InProcessChannelBuilder;
import io.grpc.inprocess.InProcessServerBuilder;
import mirror.tasks.TaskFactory;
import mirror.tasks.ThreadBasedTaskFactory; | @Before
public void clearFiles() throws Exception {
deleteDirectory(integrationTestDir);
integrationTestDir.mkdirs();
root1.mkdirs();
root2.mkdirs();
// FileUtils.touch(new File(root1, ".watchmanconfig"));
// FileUtils.touch(new File(root2, ".watchmanconfig"));
}
@After
public void shutdown() throws Exception {
// rpc.awaitTermination();
if (client != null) {
log.info("stopping client");
client.stop();
}
if (rpc != null) {
log.info("stopping server");
rpc.shutdown();
}
rpc.shutdown();
rpc.awaitTermination();
}
@Test
public void testSimpleFile() throws Exception {
startMirror();
writeFile(new File(root1, "foo.txt"), "abc");
sleep(); | // Path: src/test/java/mirror/TestUtils.java
// public static void move(final String from, final String to) {
// new Execute(new String[] { "mv", from, to }).toSystemOut();
// }
//
// Path: src/test/java/mirror/TestUtils.java
// public static String readFile(final File file) throws IOException {
// return FileUtils.readFileToString(file, UTF_8);
// }
//
// Path: src/test/java/mirror/TestUtils.java
// public static void writeFile(final File file, final String data) throws IOException {
// FileUtils.writeStringToFile(file, data, UTF_8);
// }
//
// Path: src/main/java/mirror/tasks/TaskFactory.java
// public interface TaskFactory {
//
// default TaskHandle runTask(TaskLogic logic) {
// return runTask(logic, null);
// }
//
// TaskHandle runTask(TaskLogic logic, Runnable onFailure);
//
// void stopTask(TaskLogic logic);
//
// default TaskPool newTaskPool() {
// return new TaskPool(this);
// }
//
// }
//
// Path: src/main/java/mirror/tasks/ThreadBasedTaskFactory.java
// public class ThreadBasedTaskFactory implements TaskFactory {
//
// private final ConcurrentHashMap<TaskLogic, ThreadBasedTask> tasks = new ConcurrentHashMap<>();
//
// @Override
// public TaskHandle runTask(TaskLogic logic, Runnable onFailure) {
// ThreadBasedTask task = new ThreadBasedTask(logic, onFailure, () -> {
// // we don't need to call stopTask(logic) or task.stop because the task is already stopping,
// // we just to ensure we remove this entry from our map to avoid memory leaks
// tasks.remove(logic);
// });
// tasks.put(logic, task);
// task.start();
// return () -> stopTask(logic);
// }
//
// // Note that this method isn't synchronized, as while shutting down one task,
// // while we block on task.stop completing, the task might ask us to shut down
// // one of it's child tasks, but from it's own thread, which would block.
// @Override
// public void stopTask(TaskLogic logic) {
// ThreadBasedTask task = tasks.get(logic);
// if (task != null) {
// tasks.remove(logic);
// task.stop();
// }
// }
//
// }
// Path: src/test/java/mirror/IntegrationTest.java
import static mirror.TestUtils.move;
import static mirror.TestUtils.readFile;
import static mirror.TestUtils.writeFile;
import static org.apache.commons.io.FileUtils.deleteDirectory;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.grpc.Server;
import io.grpc.inprocess.InProcessChannelBuilder;
import io.grpc.inprocess.InProcessServerBuilder;
import mirror.tasks.TaskFactory;
import mirror.tasks.ThreadBasedTaskFactory;
@Before
public void clearFiles() throws Exception {
deleteDirectory(integrationTestDir);
integrationTestDir.mkdirs();
root1.mkdirs();
root2.mkdirs();
// FileUtils.touch(new File(root1, ".watchmanconfig"));
// FileUtils.touch(new File(root2, ".watchmanconfig"));
}
@After
public void shutdown() throws Exception {
// rpc.awaitTermination();
if (client != null) {
log.info("stopping client");
client.stop();
}
if (rpc != null) {
log.info("stopping server");
rpc.shutdown();
}
rpc.shutdown();
rpc.awaitTermination();
}
@Test
public void testSimpleFile() throws Exception {
startMirror();
writeFile(new File(root1, "foo.txt"), "abc");
sleep(); | assertThat(readFile(new File(root2, "foo.txt")), is("abc")); |
stephenh/mirror | src/test/java/mirror/IntegrationTest.java | // Path: src/test/java/mirror/TestUtils.java
// public static void move(final String from, final String to) {
// new Execute(new String[] { "mv", from, to }).toSystemOut();
// }
//
// Path: src/test/java/mirror/TestUtils.java
// public static String readFile(final File file) throws IOException {
// return FileUtils.readFileToString(file, UTF_8);
// }
//
// Path: src/test/java/mirror/TestUtils.java
// public static void writeFile(final File file, final String data) throws IOException {
// FileUtils.writeStringToFile(file, data, UTF_8);
// }
//
// Path: src/main/java/mirror/tasks/TaskFactory.java
// public interface TaskFactory {
//
// default TaskHandle runTask(TaskLogic logic) {
// return runTask(logic, null);
// }
//
// TaskHandle runTask(TaskLogic logic, Runnable onFailure);
//
// void stopTask(TaskLogic logic);
//
// default TaskPool newTaskPool() {
// return new TaskPool(this);
// }
//
// }
//
// Path: src/main/java/mirror/tasks/ThreadBasedTaskFactory.java
// public class ThreadBasedTaskFactory implements TaskFactory {
//
// private final ConcurrentHashMap<TaskLogic, ThreadBasedTask> tasks = new ConcurrentHashMap<>();
//
// @Override
// public TaskHandle runTask(TaskLogic logic, Runnable onFailure) {
// ThreadBasedTask task = new ThreadBasedTask(logic, onFailure, () -> {
// // we don't need to call stopTask(logic) or task.stop because the task is already stopping,
// // we just to ensure we remove this entry from our map to avoid memory leaks
// tasks.remove(logic);
// });
// tasks.put(logic, task);
// task.start();
// return () -> stopTask(logic);
// }
//
// // Note that this method isn't synchronized, as while shutting down one task,
// // while we block on task.stop completing, the task might ask us to shut down
// // one of it's child tasks, but from it's own thread, which would block.
// @Override
// public void stopTask(TaskLogic logic) {
// ThreadBasedTask task = tasks.get(logic);
// if (task != null) {
// tasks.remove(logic);
// task.stop();
// }
// }
//
// }
| import static mirror.TestUtils.move;
import static mirror.TestUtils.readFile;
import static mirror.TestUtils.writeFile;
import static org.apache.commons.io.FileUtils.deleteDirectory;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.grpc.Server;
import io.grpc.inprocess.InProcessChannelBuilder;
import io.grpc.inprocess.InProcessServerBuilder;
import mirror.tasks.TaskFactory;
import mirror.tasks.ThreadBasedTaskFactory; | public void testSimpleDirectory() throws Exception {
startMirror();
new File(root1, "foo").mkdir();
sleep();
assertThat(new File(root2, "foo").exists(), is(true));
assertThat(new File(root2, "foo").isDirectory(), is(true));
}
@Test
public void testDeleteSimpleFile() throws Exception {
// given a file that exists in both root1/root2
writeFile(new File(root1, "foo.txt"), "abc");
writeFile(new File(root2, "foo.txt"), "abc");
startMirror();
// when one file is deleted
new File(root1, "foo.txt").delete();
sleep();
// then it's also deleted remotely
assertThat(new File(root2, "foo.txt").exists(), is(false));
}
@Test
public void testRestoreSimpleFile() throws Exception {
// given a file that exists in both root1/root2
writeFile(new File(root1, "foo.txt"), "abc");
writeFile(new File(root2, "foo.txt"), "abc");
startMirror();
// when one file is moved out of the tree
File fooOriginal = new File(root1, "foo.txt");
File fooBuild = new File("./build", "foo.txt"); | // Path: src/test/java/mirror/TestUtils.java
// public static void move(final String from, final String to) {
// new Execute(new String[] { "mv", from, to }).toSystemOut();
// }
//
// Path: src/test/java/mirror/TestUtils.java
// public static String readFile(final File file) throws IOException {
// return FileUtils.readFileToString(file, UTF_8);
// }
//
// Path: src/test/java/mirror/TestUtils.java
// public static void writeFile(final File file, final String data) throws IOException {
// FileUtils.writeStringToFile(file, data, UTF_8);
// }
//
// Path: src/main/java/mirror/tasks/TaskFactory.java
// public interface TaskFactory {
//
// default TaskHandle runTask(TaskLogic logic) {
// return runTask(logic, null);
// }
//
// TaskHandle runTask(TaskLogic logic, Runnable onFailure);
//
// void stopTask(TaskLogic logic);
//
// default TaskPool newTaskPool() {
// return new TaskPool(this);
// }
//
// }
//
// Path: src/main/java/mirror/tasks/ThreadBasedTaskFactory.java
// public class ThreadBasedTaskFactory implements TaskFactory {
//
// private final ConcurrentHashMap<TaskLogic, ThreadBasedTask> tasks = new ConcurrentHashMap<>();
//
// @Override
// public TaskHandle runTask(TaskLogic logic, Runnable onFailure) {
// ThreadBasedTask task = new ThreadBasedTask(logic, onFailure, () -> {
// // we don't need to call stopTask(logic) or task.stop because the task is already stopping,
// // we just to ensure we remove this entry from our map to avoid memory leaks
// tasks.remove(logic);
// });
// tasks.put(logic, task);
// task.start();
// return () -> stopTask(logic);
// }
//
// // Note that this method isn't synchronized, as while shutting down one task,
// // while we block on task.stop completing, the task might ask us to shut down
// // one of it's child tasks, but from it's own thread, which would block.
// @Override
// public void stopTask(TaskLogic logic) {
// ThreadBasedTask task = tasks.get(logic);
// if (task != null) {
// tasks.remove(logic);
// task.stop();
// }
// }
//
// }
// Path: src/test/java/mirror/IntegrationTest.java
import static mirror.TestUtils.move;
import static mirror.TestUtils.readFile;
import static mirror.TestUtils.writeFile;
import static org.apache.commons.io.FileUtils.deleteDirectory;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.grpc.Server;
import io.grpc.inprocess.InProcessChannelBuilder;
import io.grpc.inprocess.InProcessServerBuilder;
import mirror.tasks.TaskFactory;
import mirror.tasks.ThreadBasedTaskFactory;
public void testSimpleDirectory() throws Exception {
startMirror();
new File(root1, "foo").mkdir();
sleep();
assertThat(new File(root2, "foo").exists(), is(true));
assertThat(new File(root2, "foo").isDirectory(), is(true));
}
@Test
public void testDeleteSimpleFile() throws Exception {
// given a file that exists in both root1/root2
writeFile(new File(root1, "foo.txt"), "abc");
writeFile(new File(root2, "foo.txt"), "abc");
startMirror();
// when one file is deleted
new File(root1, "foo.txt").delete();
sleep();
// then it's also deleted remotely
assertThat(new File(root2, "foo.txt").exists(), is(false));
}
@Test
public void testRestoreSimpleFile() throws Exception {
// given a file that exists in both root1/root2
writeFile(new File(root1, "foo.txt"), "abc");
writeFile(new File(root2, "foo.txt"), "abc");
startMirror();
// when one file is moved out of the tree
File fooOriginal = new File(root1, "foo.txt");
File fooBuild = new File("./build", "foo.txt"); | move(fooOriginal.toString(), fooBuild.toString()); |
stephenh/mirror | src/test/java/mirror/IntegrationTest.java | // Path: src/test/java/mirror/TestUtils.java
// public static void move(final String from, final String to) {
// new Execute(new String[] { "mv", from, to }).toSystemOut();
// }
//
// Path: src/test/java/mirror/TestUtils.java
// public static String readFile(final File file) throws IOException {
// return FileUtils.readFileToString(file, UTF_8);
// }
//
// Path: src/test/java/mirror/TestUtils.java
// public static void writeFile(final File file, final String data) throws IOException {
// FileUtils.writeStringToFile(file, data, UTF_8);
// }
//
// Path: src/main/java/mirror/tasks/TaskFactory.java
// public interface TaskFactory {
//
// default TaskHandle runTask(TaskLogic logic) {
// return runTask(logic, null);
// }
//
// TaskHandle runTask(TaskLogic logic, Runnable onFailure);
//
// void stopTask(TaskLogic logic);
//
// default TaskPool newTaskPool() {
// return new TaskPool(this);
// }
//
// }
//
// Path: src/main/java/mirror/tasks/ThreadBasedTaskFactory.java
// public class ThreadBasedTaskFactory implements TaskFactory {
//
// private final ConcurrentHashMap<TaskLogic, ThreadBasedTask> tasks = new ConcurrentHashMap<>();
//
// @Override
// public TaskHandle runTask(TaskLogic logic, Runnable onFailure) {
// ThreadBasedTask task = new ThreadBasedTask(logic, onFailure, () -> {
// // we don't need to call stopTask(logic) or task.stop because the task is already stopping,
// // we just to ensure we remove this entry from our map to avoid memory leaks
// tasks.remove(logic);
// });
// tasks.put(logic, task);
// task.start();
// return () -> stopTask(logic);
// }
//
// // Note that this method isn't synchronized, as while shutting down one task,
// // while we block on task.stop completing, the task might ask us to shut down
// // one of it's child tasks, but from it's own thread, which would block.
// @Override
// public void stopTask(TaskLogic logic) {
// ThreadBasedTask task = tasks.get(logic);
// if (task != null) {
// tasks.remove(logic);
// task.stop();
// }
// }
//
// }
| import static mirror.TestUtils.move;
import static mirror.TestUtils.readFile;
import static mirror.TestUtils.writeFile;
import static org.apache.commons.io.FileUtils.deleteDirectory;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.grpc.Server;
import io.grpc.inprocess.InProcessChannelBuilder;
import io.grpc.inprocess.InProcessServerBuilder;
import mirror.tasks.TaskFactory;
import mirror.tasks.ThreadBasedTaskFactory; | }
@Test
public void testUpdateFileThatWasMarkedReadOnlyByCodeGenerator() throws Exception {
// given two files exist
writeFile(new File(root1, "foo.txt"), "abc1");
writeFile(new File(root2, "foo.txt"), "abc2");
// and root1's file is newer
new File(root1, "foo.txt").setLastModified(2000);
new File(root2, "foo.txt").setLastModified(1000);
// but root2's file is read only (e.g. due to overzealous code generators marking it read-only)
NativeFileAccessUtils.setReadOnly(new File(root2, "foo.txt").toPath());
// when mirror is started
startMirror();
sleep();
// then we can successfully update root2
assertThat(readFile(new File(root2, "foo.txt")), is("abc1"));
}
@Test
public void testSimpleFileThatIsEmpty() throws Exception {
startMirror();
writeFile(new File(root1, "foo.txt"), "");
sleep();
assertThat(readFile(new File(root2, "foo.txt")), is(""));
}
private void startMirror() throws Exception {
// server
int port = nextPort++; | // Path: src/test/java/mirror/TestUtils.java
// public static void move(final String from, final String to) {
// new Execute(new String[] { "mv", from, to }).toSystemOut();
// }
//
// Path: src/test/java/mirror/TestUtils.java
// public static String readFile(final File file) throws IOException {
// return FileUtils.readFileToString(file, UTF_8);
// }
//
// Path: src/test/java/mirror/TestUtils.java
// public static void writeFile(final File file, final String data) throws IOException {
// FileUtils.writeStringToFile(file, data, UTF_8);
// }
//
// Path: src/main/java/mirror/tasks/TaskFactory.java
// public interface TaskFactory {
//
// default TaskHandle runTask(TaskLogic logic) {
// return runTask(logic, null);
// }
//
// TaskHandle runTask(TaskLogic logic, Runnable onFailure);
//
// void stopTask(TaskLogic logic);
//
// default TaskPool newTaskPool() {
// return new TaskPool(this);
// }
//
// }
//
// Path: src/main/java/mirror/tasks/ThreadBasedTaskFactory.java
// public class ThreadBasedTaskFactory implements TaskFactory {
//
// private final ConcurrentHashMap<TaskLogic, ThreadBasedTask> tasks = new ConcurrentHashMap<>();
//
// @Override
// public TaskHandle runTask(TaskLogic logic, Runnable onFailure) {
// ThreadBasedTask task = new ThreadBasedTask(logic, onFailure, () -> {
// // we don't need to call stopTask(logic) or task.stop because the task is already stopping,
// // we just to ensure we remove this entry from our map to avoid memory leaks
// tasks.remove(logic);
// });
// tasks.put(logic, task);
// task.start();
// return () -> stopTask(logic);
// }
//
// // Note that this method isn't synchronized, as while shutting down one task,
// // while we block on task.stop completing, the task might ask us to shut down
// // one of it's child tasks, but from it's own thread, which would block.
// @Override
// public void stopTask(TaskLogic logic) {
// ThreadBasedTask task = tasks.get(logic);
// if (task != null) {
// tasks.remove(logic);
// task.stop();
// }
// }
//
// }
// Path: src/test/java/mirror/IntegrationTest.java
import static mirror.TestUtils.move;
import static mirror.TestUtils.readFile;
import static mirror.TestUtils.writeFile;
import static org.apache.commons.io.FileUtils.deleteDirectory;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.grpc.Server;
import io.grpc.inprocess.InProcessChannelBuilder;
import io.grpc.inprocess.InProcessServerBuilder;
import mirror.tasks.TaskFactory;
import mirror.tasks.ThreadBasedTaskFactory;
}
@Test
public void testUpdateFileThatWasMarkedReadOnlyByCodeGenerator() throws Exception {
// given two files exist
writeFile(new File(root1, "foo.txt"), "abc1");
writeFile(new File(root2, "foo.txt"), "abc2");
// and root1's file is newer
new File(root1, "foo.txt").setLastModified(2000);
new File(root2, "foo.txt").setLastModified(1000);
// but root2's file is read only (e.g. due to overzealous code generators marking it read-only)
NativeFileAccessUtils.setReadOnly(new File(root2, "foo.txt").toPath());
// when mirror is started
startMirror();
sleep();
// then we can successfully update root2
assertThat(readFile(new File(root2, "foo.txt")), is("abc1"));
}
@Test
public void testSimpleFileThatIsEmpty() throws Exception {
startMirror();
writeFile(new File(root1, "foo.txt"), "");
sleep();
assertThat(readFile(new File(root2, "foo.txt")), is(""));
}
private void startMirror() throws Exception {
// server
int port = nextPort++; | TaskFactory serverTaskFactory = new ThreadBasedTaskFactory(); |
stephenh/mirror | src/test/java/mirror/IntegrationTest.java | // Path: src/test/java/mirror/TestUtils.java
// public static void move(final String from, final String to) {
// new Execute(new String[] { "mv", from, to }).toSystemOut();
// }
//
// Path: src/test/java/mirror/TestUtils.java
// public static String readFile(final File file) throws IOException {
// return FileUtils.readFileToString(file, UTF_8);
// }
//
// Path: src/test/java/mirror/TestUtils.java
// public static void writeFile(final File file, final String data) throws IOException {
// FileUtils.writeStringToFile(file, data, UTF_8);
// }
//
// Path: src/main/java/mirror/tasks/TaskFactory.java
// public interface TaskFactory {
//
// default TaskHandle runTask(TaskLogic logic) {
// return runTask(logic, null);
// }
//
// TaskHandle runTask(TaskLogic logic, Runnable onFailure);
//
// void stopTask(TaskLogic logic);
//
// default TaskPool newTaskPool() {
// return new TaskPool(this);
// }
//
// }
//
// Path: src/main/java/mirror/tasks/ThreadBasedTaskFactory.java
// public class ThreadBasedTaskFactory implements TaskFactory {
//
// private final ConcurrentHashMap<TaskLogic, ThreadBasedTask> tasks = new ConcurrentHashMap<>();
//
// @Override
// public TaskHandle runTask(TaskLogic logic, Runnable onFailure) {
// ThreadBasedTask task = new ThreadBasedTask(logic, onFailure, () -> {
// // we don't need to call stopTask(logic) or task.stop because the task is already stopping,
// // we just to ensure we remove this entry from our map to avoid memory leaks
// tasks.remove(logic);
// });
// tasks.put(logic, task);
// task.start();
// return () -> stopTask(logic);
// }
//
// // Note that this method isn't synchronized, as while shutting down one task,
// // while we block on task.stop completing, the task might ask us to shut down
// // one of it's child tasks, but from it's own thread, which would block.
// @Override
// public void stopTask(TaskLogic logic) {
// ThreadBasedTask task = tasks.get(logic);
// if (task != null) {
// tasks.remove(logic);
// task.stop();
// }
// }
//
// }
| import static mirror.TestUtils.move;
import static mirror.TestUtils.readFile;
import static mirror.TestUtils.writeFile;
import static org.apache.commons.io.FileUtils.deleteDirectory;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.grpc.Server;
import io.grpc.inprocess.InProcessChannelBuilder;
import io.grpc.inprocess.InProcessServerBuilder;
import mirror.tasks.TaskFactory;
import mirror.tasks.ThreadBasedTaskFactory; | }
@Test
public void testUpdateFileThatWasMarkedReadOnlyByCodeGenerator() throws Exception {
// given two files exist
writeFile(new File(root1, "foo.txt"), "abc1");
writeFile(new File(root2, "foo.txt"), "abc2");
// and root1's file is newer
new File(root1, "foo.txt").setLastModified(2000);
new File(root2, "foo.txt").setLastModified(1000);
// but root2's file is read only (e.g. due to overzealous code generators marking it read-only)
NativeFileAccessUtils.setReadOnly(new File(root2, "foo.txt").toPath());
// when mirror is started
startMirror();
sleep();
// then we can successfully update root2
assertThat(readFile(new File(root2, "foo.txt")), is("abc1"));
}
@Test
public void testSimpleFileThatIsEmpty() throws Exception {
startMirror();
writeFile(new File(root1, "foo.txt"), "");
sleep();
assertThat(readFile(new File(root2, "foo.txt")), is(""));
}
private void startMirror() throws Exception {
// server
int port = nextPort++; | // Path: src/test/java/mirror/TestUtils.java
// public static void move(final String from, final String to) {
// new Execute(new String[] { "mv", from, to }).toSystemOut();
// }
//
// Path: src/test/java/mirror/TestUtils.java
// public static String readFile(final File file) throws IOException {
// return FileUtils.readFileToString(file, UTF_8);
// }
//
// Path: src/test/java/mirror/TestUtils.java
// public static void writeFile(final File file, final String data) throws IOException {
// FileUtils.writeStringToFile(file, data, UTF_8);
// }
//
// Path: src/main/java/mirror/tasks/TaskFactory.java
// public interface TaskFactory {
//
// default TaskHandle runTask(TaskLogic logic) {
// return runTask(logic, null);
// }
//
// TaskHandle runTask(TaskLogic logic, Runnable onFailure);
//
// void stopTask(TaskLogic logic);
//
// default TaskPool newTaskPool() {
// return new TaskPool(this);
// }
//
// }
//
// Path: src/main/java/mirror/tasks/ThreadBasedTaskFactory.java
// public class ThreadBasedTaskFactory implements TaskFactory {
//
// private final ConcurrentHashMap<TaskLogic, ThreadBasedTask> tasks = new ConcurrentHashMap<>();
//
// @Override
// public TaskHandle runTask(TaskLogic logic, Runnable onFailure) {
// ThreadBasedTask task = new ThreadBasedTask(logic, onFailure, () -> {
// // we don't need to call stopTask(logic) or task.stop because the task is already stopping,
// // we just to ensure we remove this entry from our map to avoid memory leaks
// tasks.remove(logic);
// });
// tasks.put(logic, task);
// task.start();
// return () -> stopTask(logic);
// }
//
// // Note that this method isn't synchronized, as while shutting down one task,
// // while we block on task.stop completing, the task might ask us to shut down
// // one of it's child tasks, but from it's own thread, which would block.
// @Override
// public void stopTask(TaskLogic logic) {
// ThreadBasedTask task = tasks.get(logic);
// if (task != null) {
// tasks.remove(logic);
// task.stop();
// }
// }
//
// }
// Path: src/test/java/mirror/IntegrationTest.java
import static mirror.TestUtils.move;
import static mirror.TestUtils.readFile;
import static mirror.TestUtils.writeFile;
import static org.apache.commons.io.FileUtils.deleteDirectory;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.grpc.Server;
import io.grpc.inprocess.InProcessChannelBuilder;
import io.grpc.inprocess.InProcessServerBuilder;
import mirror.tasks.TaskFactory;
import mirror.tasks.ThreadBasedTaskFactory;
}
@Test
public void testUpdateFileThatWasMarkedReadOnlyByCodeGenerator() throws Exception {
// given two files exist
writeFile(new File(root1, "foo.txt"), "abc1");
writeFile(new File(root2, "foo.txt"), "abc2");
// and root1's file is newer
new File(root1, "foo.txt").setLastModified(2000);
new File(root2, "foo.txt").setLastModified(1000);
// but root2's file is read only (e.g. due to overzealous code generators marking it read-only)
NativeFileAccessUtils.setReadOnly(new File(root2, "foo.txt").toPath());
// when mirror is started
startMirror();
sleep();
// then we can successfully update root2
assertThat(readFile(new File(root2, "foo.txt")), is("abc1"));
}
@Test
public void testSimpleFileThatIsEmpty() throws Exception {
startMirror();
writeFile(new File(root1, "foo.txt"), "");
sleep();
assertThat(readFile(new File(root2, "foo.txt")), is(""));
}
private void startMirror() throws Exception {
// server
int port = nextPort++; | TaskFactory serverTaskFactory = new ThreadBasedTaskFactory(); |
stephenh/mirror | src/test/java/mirror/WatchServiceFileWatcherTest.java | // Path: src/test/java/mirror/TestUtils.java
// public static void move(final String from, final String to) {
// new Execute(new String[] { "mv", from, to }).toSystemOut();
// }
//
// Path: src/test/java/mirror/TestUtils.java
// public static void writeFile(final File file, final String data) throws IOException {
// FileUtils.writeStringToFile(file, data, UTF_8);
// }
//
// Path: src/main/java/mirror/tasks/TaskFactory.java
// public interface TaskFactory {
//
// default TaskHandle runTask(TaskLogic logic) {
// return runTask(logic, null);
// }
//
// TaskHandle runTask(TaskLogic logic, Runnable onFailure);
//
// void stopTask(TaskLogic logic);
//
// default TaskPool newTaskPool() {
// return new TaskPool(this);
// }
//
// }
//
// Path: src/main/java/mirror/tasks/ThreadBasedTaskFactory.java
// public class ThreadBasedTaskFactory implements TaskFactory {
//
// private final ConcurrentHashMap<TaskLogic, ThreadBasedTask> tasks = new ConcurrentHashMap<>();
//
// @Override
// public TaskHandle runTask(TaskLogic logic, Runnable onFailure) {
// ThreadBasedTask task = new ThreadBasedTask(logic, onFailure, () -> {
// // we don't need to call stopTask(logic) or task.stop because the task is already stopping,
// // we just to ensure we remove this entry from our map to avoid memory leaks
// tasks.remove(logic);
// });
// tasks.put(logic, task);
// task.start();
// return () -> stopTask(logic);
// }
//
// // Note that this method isn't synchronized, as while shutting down one task,
// // while we block on task.stop completing, the task might ask us to shut down
// // one of it's child tasks, but from it's own thread, which would block.
// @Override
// public void stopTask(TaskLogic logic) {
// ThreadBasedTask task = tasks.get(logic);
// if (task != null) {
// tasks.remove(logic);
// task.stop();
// }
// }
//
// }
| import static mirror.TestUtils.move;
import static mirror.TestUtils.writeFile;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import java.io.File;
import java.nio.file.FileSystems;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import org.apache.commons.io.FileUtils;
import org.jooq.lambda.Seq;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import mirror.tasks.TaskFactory;
import mirror.tasks.ThreadBasedTaskFactory; | package mirror;
/**
* Tests {@link WatchServiceFileWatcher}.
*
* Currently ignored because when files are created, e.g. foo.txt,
* {@link WatchServiceFileWatcher} will sometimes send one update
* (create) and sometimes send two.
*
* This is just what the underlying inotify events are, so it is not
* wrong, but it makes test assertions annoying.
*/
@Ignore
public class WatchServiceFileWatcherTest {
static {
LoggingConfig.init();
}
private static final File dir = new File("./build/FileWatcherTest"); | // Path: src/test/java/mirror/TestUtils.java
// public static void move(final String from, final String to) {
// new Execute(new String[] { "mv", from, to }).toSystemOut();
// }
//
// Path: src/test/java/mirror/TestUtils.java
// public static void writeFile(final File file, final String data) throws IOException {
// FileUtils.writeStringToFile(file, data, UTF_8);
// }
//
// Path: src/main/java/mirror/tasks/TaskFactory.java
// public interface TaskFactory {
//
// default TaskHandle runTask(TaskLogic logic) {
// return runTask(logic, null);
// }
//
// TaskHandle runTask(TaskLogic logic, Runnable onFailure);
//
// void stopTask(TaskLogic logic);
//
// default TaskPool newTaskPool() {
// return new TaskPool(this);
// }
//
// }
//
// Path: src/main/java/mirror/tasks/ThreadBasedTaskFactory.java
// public class ThreadBasedTaskFactory implements TaskFactory {
//
// private final ConcurrentHashMap<TaskLogic, ThreadBasedTask> tasks = new ConcurrentHashMap<>();
//
// @Override
// public TaskHandle runTask(TaskLogic logic, Runnable onFailure) {
// ThreadBasedTask task = new ThreadBasedTask(logic, onFailure, () -> {
// // we don't need to call stopTask(logic) or task.stop because the task is already stopping,
// // we just to ensure we remove this entry from our map to avoid memory leaks
// tasks.remove(logic);
// });
// tasks.put(logic, task);
// task.start();
// return () -> stopTask(logic);
// }
//
// // Note that this method isn't synchronized, as while shutting down one task,
// // while we block on task.stop completing, the task might ask us to shut down
// // one of it's child tasks, but from it's own thread, which would block.
// @Override
// public void stopTask(TaskLogic logic) {
// ThreadBasedTask task = tasks.get(logic);
// if (task != null) {
// tasks.remove(logic);
// task.stop();
// }
// }
//
// }
// Path: src/test/java/mirror/WatchServiceFileWatcherTest.java
import static mirror.TestUtils.move;
import static mirror.TestUtils.writeFile;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import java.io.File;
import java.nio.file.FileSystems;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import org.apache.commons.io.FileUtils;
import org.jooq.lambda.Seq;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import mirror.tasks.TaskFactory;
import mirror.tasks.ThreadBasedTaskFactory;
package mirror;
/**
* Tests {@link WatchServiceFileWatcher}.
*
* Currently ignored because when files are created, e.g. foo.txt,
* {@link WatchServiceFileWatcher} will sometimes send one update
* (create) and sometimes send two.
*
* This is just what the underlying inotify events are, so it is not
* wrong, but it makes test assertions annoying.
*/
@Ignore
public class WatchServiceFileWatcherTest {
static {
LoggingConfig.init();
}
private static final File dir = new File("./build/FileWatcherTest"); | private final TaskFactory taskFactory = new ThreadBasedTaskFactory(); |
stephenh/mirror | src/test/java/mirror/WatchServiceFileWatcherTest.java | // Path: src/test/java/mirror/TestUtils.java
// public static void move(final String from, final String to) {
// new Execute(new String[] { "mv", from, to }).toSystemOut();
// }
//
// Path: src/test/java/mirror/TestUtils.java
// public static void writeFile(final File file, final String data) throws IOException {
// FileUtils.writeStringToFile(file, data, UTF_8);
// }
//
// Path: src/main/java/mirror/tasks/TaskFactory.java
// public interface TaskFactory {
//
// default TaskHandle runTask(TaskLogic logic) {
// return runTask(logic, null);
// }
//
// TaskHandle runTask(TaskLogic logic, Runnable onFailure);
//
// void stopTask(TaskLogic logic);
//
// default TaskPool newTaskPool() {
// return new TaskPool(this);
// }
//
// }
//
// Path: src/main/java/mirror/tasks/ThreadBasedTaskFactory.java
// public class ThreadBasedTaskFactory implements TaskFactory {
//
// private final ConcurrentHashMap<TaskLogic, ThreadBasedTask> tasks = new ConcurrentHashMap<>();
//
// @Override
// public TaskHandle runTask(TaskLogic logic, Runnable onFailure) {
// ThreadBasedTask task = new ThreadBasedTask(logic, onFailure, () -> {
// // we don't need to call stopTask(logic) or task.stop because the task is already stopping,
// // we just to ensure we remove this entry from our map to avoid memory leaks
// tasks.remove(logic);
// });
// tasks.put(logic, task);
// task.start();
// return () -> stopTask(logic);
// }
//
// // Note that this method isn't synchronized, as while shutting down one task,
// // while we block on task.stop completing, the task might ask us to shut down
// // one of it's child tasks, but from it's own thread, which would block.
// @Override
// public void stopTask(TaskLogic logic) {
// ThreadBasedTask task = tasks.get(logic);
// if (task != null) {
// tasks.remove(logic);
// task.stop();
// }
// }
//
// }
| import static mirror.TestUtils.move;
import static mirror.TestUtils.writeFile;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import java.io.File;
import java.nio.file.FileSystems;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import org.apache.commons.io.FileUtils;
import org.jooq.lambda.Seq;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import mirror.tasks.TaskFactory;
import mirror.tasks.ThreadBasedTaskFactory; | package mirror;
/**
* Tests {@link WatchServiceFileWatcher}.
*
* Currently ignored because when files are created, e.g. foo.txt,
* {@link WatchServiceFileWatcher} will sometimes send one update
* (create) and sometimes send two.
*
* This is just what the underlying inotify events are, so it is not
* wrong, but it makes test assertions annoying.
*/
@Ignore
public class WatchServiceFileWatcherTest {
static {
LoggingConfig.init();
}
private static final File dir = new File("./build/FileWatcherTest"); | // Path: src/test/java/mirror/TestUtils.java
// public static void move(final String from, final String to) {
// new Execute(new String[] { "mv", from, to }).toSystemOut();
// }
//
// Path: src/test/java/mirror/TestUtils.java
// public static void writeFile(final File file, final String data) throws IOException {
// FileUtils.writeStringToFile(file, data, UTF_8);
// }
//
// Path: src/main/java/mirror/tasks/TaskFactory.java
// public interface TaskFactory {
//
// default TaskHandle runTask(TaskLogic logic) {
// return runTask(logic, null);
// }
//
// TaskHandle runTask(TaskLogic logic, Runnable onFailure);
//
// void stopTask(TaskLogic logic);
//
// default TaskPool newTaskPool() {
// return new TaskPool(this);
// }
//
// }
//
// Path: src/main/java/mirror/tasks/ThreadBasedTaskFactory.java
// public class ThreadBasedTaskFactory implements TaskFactory {
//
// private final ConcurrentHashMap<TaskLogic, ThreadBasedTask> tasks = new ConcurrentHashMap<>();
//
// @Override
// public TaskHandle runTask(TaskLogic logic, Runnable onFailure) {
// ThreadBasedTask task = new ThreadBasedTask(logic, onFailure, () -> {
// // we don't need to call stopTask(logic) or task.stop because the task is already stopping,
// // we just to ensure we remove this entry from our map to avoid memory leaks
// tasks.remove(logic);
// });
// tasks.put(logic, task);
// task.start();
// return () -> stopTask(logic);
// }
//
// // Note that this method isn't synchronized, as while shutting down one task,
// // while we block on task.stop completing, the task might ask us to shut down
// // one of it's child tasks, but from it's own thread, which would block.
// @Override
// public void stopTask(TaskLogic logic) {
// ThreadBasedTask task = tasks.get(logic);
// if (task != null) {
// tasks.remove(logic);
// task.stop();
// }
// }
//
// }
// Path: src/test/java/mirror/WatchServiceFileWatcherTest.java
import static mirror.TestUtils.move;
import static mirror.TestUtils.writeFile;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import java.io.File;
import java.nio.file.FileSystems;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import org.apache.commons.io.FileUtils;
import org.jooq.lambda.Seq;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import mirror.tasks.TaskFactory;
import mirror.tasks.ThreadBasedTaskFactory;
package mirror;
/**
* Tests {@link WatchServiceFileWatcher}.
*
* Currently ignored because when files are created, e.g. foo.txt,
* {@link WatchServiceFileWatcher} will sometimes send one update
* (create) and sometimes send two.
*
* This is just what the underlying inotify events are, so it is not
* wrong, but it makes test assertions annoying.
*/
@Ignore
public class WatchServiceFileWatcherTest {
static {
LoggingConfig.init();
}
private static final File dir = new File("./build/FileWatcherTest"); | private final TaskFactory taskFactory = new ThreadBasedTaskFactory(); |
stephenh/mirror | src/test/java/mirror/WatchServiceFileWatcherTest.java | // Path: src/test/java/mirror/TestUtils.java
// public static void move(final String from, final String to) {
// new Execute(new String[] { "mv", from, to }).toSystemOut();
// }
//
// Path: src/test/java/mirror/TestUtils.java
// public static void writeFile(final File file, final String data) throws IOException {
// FileUtils.writeStringToFile(file, data, UTF_8);
// }
//
// Path: src/main/java/mirror/tasks/TaskFactory.java
// public interface TaskFactory {
//
// default TaskHandle runTask(TaskLogic logic) {
// return runTask(logic, null);
// }
//
// TaskHandle runTask(TaskLogic logic, Runnable onFailure);
//
// void stopTask(TaskLogic logic);
//
// default TaskPool newTaskPool() {
// return new TaskPool(this);
// }
//
// }
//
// Path: src/main/java/mirror/tasks/ThreadBasedTaskFactory.java
// public class ThreadBasedTaskFactory implements TaskFactory {
//
// private final ConcurrentHashMap<TaskLogic, ThreadBasedTask> tasks = new ConcurrentHashMap<>();
//
// @Override
// public TaskHandle runTask(TaskLogic logic, Runnable onFailure) {
// ThreadBasedTask task = new ThreadBasedTask(logic, onFailure, () -> {
// // we don't need to call stopTask(logic) or task.stop because the task is already stopping,
// // we just to ensure we remove this entry from our map to avoid memory leaks
// tasks.remove(logic);
// });
// tasks.put(logic, task);
// task.start();
// return () -> stopTask(logic);
// }
//
// // Note that this method isn't synchronized, as while shutting down one task,
// // while we block on task.stop completing, the task might ask us to shut down
// // one of it's child tasks, but from it's own thread, which would block.
// @Override
// public void stopTask(TaskLogic logic) {
// ThreadBasedTask task = tasks.get(logic);
// if (task != null) {
// tasks.remove(logic);
// task.stop();
// }
// }
//
// }
| import static mirror.TestUtils.move;
import static mirror.TestUtils.writeFile;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import java.io.File;
import java.nio.file.FileSystems;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import org.apache.commons.io.FileUtils;
import org.jooq.lambda.Seq;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import mirror.tasks.TaskFactory;
import mirror.tasks.ThreadBasedTaskFactory; | package mirror;
/**
* Tests {@link WatchServiceFileWatcher}.
*
* Currently ignored because when files are created, e.g. foo.txt,
* {@link WatchServiceFileWatcher} will sometimes send one update
* (create) and sometimes send two.
*
* This is just what the underlying inotify events are, so it is not
* wrong, but it makes test assertions annoying.
*/
@Ignore
public class WatchServiceFileWatcherTest {
static {
LoggingConfig.init();
}
private static final File dir = new File("./build/FileWatcherTest");
private final TaskFactory taskFactory = new ThreadBasedTaskFactory();
private final BlockingQueue<Update> queue = new ArrayBlockingQueue<>(100);
private FileWatcher watcher;
@Before
public void clearFiles() throws Exception {
if (dir.exists()) {
FileUtils.forceDelete(dir);
}
dir.mkdirs();
watcher = new WatchServiceFileWatcher(taskFactory, FileSystems.getDefault().newWatchService(), dir.toPath(), queue);
watcher.performInitialScan();
taskFactory.runTask(watcher);
}
@After
public void stopWatcher() throws Exception {
taskFactory.stopTask(watcher);
}
@Test
public void testDirectoryRename() throws Exception {
// given a directory is created
File dir1 = new File(dir, "dir1");
dir1.mkdir();
// and then renamed
File dir2 = new File(dir, "dir2"); | // Path: src/test/java/mirror/TestUtils.java
// public static void move(final String from, final String to) {
// new Execute(new String[] { "mv", from, to }).toSystemOut();
// }
//
// Path: src/test/java/mirror/TestUtils.java
// public static void writeFile(final File file, final String data) throws IOException {
// FileUtils.writeStringToFile(file, data, UTF_8);
// }
//
// Path: src/main/java/mirror/tasks/TaskFactory.java
// public interface TaskFactory {
//
// default TaskHandle runTask(TaskLogic logic) {
// return runTask(logic, null);
// }
//
// TaskHandle runTask(TaskLogic logic, Runnable onFailure);
//
// void stopTask(TaskLogic logic);
//
// default TaskPool newTaskPool() {
// return new TaskPool(this);
// }
//
// }
//
// Path: src/main/java/mirror/tasks/ThreadBasedTaskFactory.java
// public class ThreadBasedTaskFactory implements TaskFactory {
//
// private final ConcurrentHashMap<TaskLogic, ThreadBasedTask> tasks = new ConcurrentHashMap<>();
//
// @Override
// public TaskHandle runTask(TaskLogic logic, Runnable onFailure) {
// ThreadBasedTask task = new ThreadBasedTask(logic, onFailure, () -> {
// // we don't need to call stopTask(logic) or task.stop because the task is already stopping,
// // we just to ensure we remove this entry from our map to avoid memory leaks
// tasks.remove(logic);
// });
// tasks.put(logic, task);
// task.start();
// return () -> stopTask(logic);
// }
//
// // Note that this method isn't synchronized, as while shutting down one task,
// // while we block on task.stop completing, the task might ask us to shut down
// // one of it's child tasks, but from it's own thread, which would block.
// @Override
// public void stopTask(TaskLogic logic) {
// ThreadBasedTask task = tasks.get(logic);
// if (task != null) {
// tasks.remove(logic);
// task.stop();
// }
// }
//
// }
// Path: src/test/java/mirror/WatchServiceFileWatcherTest.java
import static mirror.TestUtils.move;
import static mirror.TestUtils.writeFile;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import java.io.File;
import java.nio.file.FileSystems;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import org.apache.commons.io.FileUtils;
import org.jooq.lambda.Seq;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import mirror.tasks.TaskFactory;
import mirror.tasks.ThreadBasedTaskFactory;
package mirror;
/**
* Tests {@link WatchServiceFileWatcher}.
*
* Currently ignored because when files are created, e.g. foo.txt,
* {@link WatchServiceFileWatcher} will sometimes send one update
* (create) and sometimes send two.
*
* This is just what the underlying inotify events are, so it is not
* wrong, but it makes test assertions annoying.
*/
@Ignore
public class WatchServiceFileWatcherTest {
static {
LoggingConfig.init();
}
private static final File dir = new File("./build/FileWatcherTest");
private final TaskFactory taskFactory = new ThreadBasedTaskFactory();
private final BlockingQueue<Update> queue = new ArrayBlockingQueue<>(100);
private FileWatcher watcher;
@Before
public void clearFiles() throws Exception {
if (dir.exists()) {
FileUtils.forceDelete(dir);
}
dir.mkdirs();
watcher = new WatchServiceFileWatcher(taskFactory, FileSystems.getDefault().newWatchService(), dir.toPath(), queue);
watcher.performInitialScan();
taskFactory.runTask(watcher);
}
@After
public void stopWatcher() throws Exception {
taskFactory.stopTask(watcher);
}
@Test
public void testDirectoryRename() throws Exception {
// given a directory is created
File dir1 = new File(dir, "dir1");
dir1.mkdir();
// and then renamed
File dir2 = new File(dir, "dir2"); | move(dir1.toString(), dir2.toString()); |
stephenh/mirror | src/test/java/mirror/WatchServiceFileWatcherTest.java | // Path: src/test/java/mirror/TestUtils.java
// public static void move(final String from, final String to) {
// new Execute(new String[] { "mv", from, to }).toSystemOut();
// }
//
// Path: src/test/java/mirror/TestUtils.java
// public static void writeFile(final File file, final String data) throws IOException {
// FileUtils.writeStringToFile(file, data, UTF_8);
// }
//
// Path: src/main/java/mirror/tasks/TaskFactory.java
// public interface TaskFactory {
//
// default TaskHandle runTask(TaskLogic logic) {
// return runTask(logic, null);
// }
//
// TaskHandle runTask(TaskLogic logic, Runnable onFailure);
//
// void stopTask(TaskLogic logic);
//
// default TaskPool newTaskPool() {
// return new TaskPool(this);
// }
//
// }
//
// Path: src/main/java/mirror/tasks/ThreadBasedTaskFactory.java
// public class ThreadBasedTaskFactory implements TaskFactory {
//
// private final ConcurrentHashMap<TaskLogic, ThreadBasedTask> tasks = new ConcurrentHashMap<>();
//
// @Override
// public TaskHandle runTask(TaskLogic logic, Runnable onFailure) {
// ThreadBasedTask task = new ThreadBasedTask(logic, onFailure, () -> {
// // we don't need to call stopTask(logic) or task.stop because the task is already stopping,
// // we just to ensure we remove this entry from our map to avoid memory leaks
// tasks.remove(logic);
// });
// tasks.put(logic, task);
// task.start();
// return () -> stopTask(logic);
// }
//
// // Note that this method isn't synchronized, as while shutting down one task,
// // while we block on task.stop completing, the task might ask us to shut down
// // one of it's child tasks, but from it's own thread, which would block.
// @Override
// public void stopTask(TaskLogic logic) {
// ThreadBasedTask task = tasks.get(logic);
// if (task != null) {
// tasks.remove(logic);
// task.stop();
// }
// }
//
// }
| import static mirror.TestUtils.move;
import static mirror.TestUtils.writeFile;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import java.io.File;
import java.nio.file.FileSystems;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import org.apache.commons.io.FileUtils;
import org.jooq.lambda.Seq;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import mirror.tasks.TaskFactory;
import mirror.tasks.ThreadBasedTaskFactory; | package mirror;
/**
* Tests {@link WatchServiceFileWatcher}.
*
* Currently ignored because when files are created, e.g. foo.txt,
* {@link WatchServiceFileWatcher} will sometimes send one update
* (create) and sometimes send two.
*
* This is just what the underlying inotify events are, so it is not
* wrong, but it makes test assertions annoying.
*/
@Ignore
public class WatchServiceFileWatcherTest {
static {
LoggingConfig.init();
}
private static final File dir = new File("./build/FileWatcherTest");
private final TaskFactory taskFactory = new ThreadBasedTaskFactory();
private final BlockingQueue<Update> queue = new ArrayBlockingQueue<>(100);
private FileWatcher watcher;
@Before
public void clearFiles() throws Exception {
if (dir.exists()) {
FileUtils.forceDelete(dir);
}
dir.mkdirs();
watcher = new WatchServiceFileWatcher(taskFactory, FileSystems.getDefault().newWatchService(), dir.toPath(), queue);
watcher.performInitialScan();
taskFactory.runTask(watcher);
}
@After
public void stopWatcher() throws Exception {
taskFactory.stopTask(watcher);
}
@Test
public void testDirectoryRename() throws Exception {
// given a directory is created
File dir1 = new File(dir, "dir1");
dir1.mkdir();
// and then renamed
File dir2 = new File(dir, "dir2");
move(dir1.toString(), dir2.toString()); | // Path: src/test/java/mirror/TestUtils.java
// public static void move(final String from, final String to) {
// new Execute(new String[] { "mv", from, to }).toSystemOut();
// }
//
// Path: src/test/java/mirror/TestUtils.java
// public static void writeFile(final File file, final String data) throws IOException {
// FileUtils.writeStringToFile(file, data, UTF_8);
// }
//
// Path: src/main/java/mirror/tasks/TaskFactory.java
// public interface TaskFactory {
//
// default TaskHandle runTask(TaskLogic logic) {
// return runTask(logic, null);
// }
//
// TaskHandle runTask(TaskLogic logic, Runnable onFailure);
//
// void stopTask(TaskLogic logic);
//
// default TaskPool newTaskPool() {
// return new TaskPool(this);
// }
//
// }
//
// Path: src/main/java/mirror/tasks/ThreadBasedTaskFactory.java
// public class ThreadBasedTaskFactory implements TaskFactory {
//
// private final ConcurrentHashMap<TaskLogic, ThreadBasedTask> tasks = new ConcurrentHashMap<>();
//
// @Override
// public TaskHandle runTask(TaskLogic logic, Runnable onFailure) {
// ThreadBasedTask task = new ThreadBasedTask(logic, onFailure, () -> {
// // we don't need to call stopTask(logic) or task.stop because the task is already stopping,
// // we just to ensure we remove this entry from our map to avoid memory leaks
// tasks.remove(logic);
// });
// tasks.put(logic, task);
// task.start();
// return () -> stopTask(logic);
// }
//
// // Note that this method isn't synchronized, as while shutting down one task,
// // while we block on task.stop completing, the task might ask us to shut down
// // one of it's child tasks, but from it's own thread, which would block.
// @Override
// public void stopTask(TaskLogic logic) {
// ThreadBasedTask task = tasks.get(logic);
// if (task != null) {
// tasks.remove(logic);
// task.stop();
// }
// }
//
// }
// Path: src/test/java/mirror/WatchServiceFileWatcherTest.java
import static mirror.TestUtils.move;
import static mirror.TestUtils.writeFile;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import java.io.File;
import java.nio.file.FileSystems;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import org.apache.commons.io.FileUtils;
import org.jooq.lambda.Seq;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import mirror.tasks.TaskFactory;
import mirror.tasks.ThreadBasedTaskFactory;
package mirror;
/**
* Tests {@link WatchServiceFileWatcher}.
*
* Currently ignored because when files are created, e.g. foo.txt,
* {@link WatchServiceFileWatcher} will sometimes send one update
* (create) and sometimes send two.
*
* This is just what the underlying inotify events are, so it is not
* wrong, but it makes test assertions annoying.
*/
@Ignore
public class WatchServiceFileWatcherTest {
static {
LoggingConfig.init();
}
private static final File dir = new File("./build/FileWatcherTest");
private final TaskFactory taskFactory = new ThreadBasedTaskFactory();
private final BlockingQueue<Update> queue = new ArrayBlockingQueue<>(100);
private FileWatcher watcher;
@Before
public void clearFiles() throws Exception {
if (dir.exists()) {
FileUtils.forceDelete(dir);
}
dir.mkdirs();
watcher = new WatchServiceFileWatcher(taskFactory, FileSystems.getDefault().newWatchService(), dir.toPath(), queue);
watcher.performInitialScan();
taskFactory.runTask(watcher);
}
@After
public void stopWatcher() throws Exception {
taskFactory.stopTask(watcher);
}
@Test
public void testDirectoryRename() throws Exception {
// given a directory is created
File dir1 = new File(dir, "dir1");
dir1.mkdir();
// and then renamed
File dir2 = new File(dir, "dir2");
move(dir1.toString(), dir2.toString()); | writeFile(new File(dir2, "foo.txt"), "abc"); |
antest1/kcanotify | app/src/main/java/com/antest1/kcanotify/KcaExpeditionTableViewAdpater.java | // Path: app/src/main/java/com/antest1/kcanotify/KcaApiData.java
// public static JsonObject getExpeditionInfo(int mission_no, String locale) {
// JsonObject data = null;
// int mission_key = mission_no;
// String key = String.valueOf(mission_key);
// if (!kcExpeditionData.has(key)) {
// if (mission_no % 2 == 1) key = "203";
// else key = "204";
// }
// JsonObject rawdata = kcExpeditionData.getAsJsonObject(key);
// data = new JsonParser().parse(rawdata.toString()).getAsJsonObject();
// JsonObject name = data.getAsJsonObject("name");
// if (name.has(locale)) {
// data.addProperty("name", name.get(locale).getAsString());
// } else {
// data.addProperty("name", name.get("en").getAsString());
// }
// return data;
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaApiData.java
// public static String getShipTypeAbbr(int idx) {
// if (kcStypeData != null && idx < kcStypeData.size()) {
// return kcStypeData.get(idx).getAsString();
// } else {
// return "";
// }
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static String joinStr(List<String> list, String delim) {
// String resultStr = "";
// if (list.size() > 0) {
// int i;
// for (i = 0; i < list.size() - 1; i++) {
// resultStr = resultStr.concat(list.get(i));
// resultStr = resultStr.concat(delim);
// }
// resultStr = resultStr.concat(list.get(i));
// }
// return resultStr;
// }
| import android.content.Context;
import androidx.core.content.ContextCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import static com.antest1.kcanotify.KcaApiData.getExpeditionInfo;
import static com.antest1.kcanotify.KcaApiData.getShipTypeAbbr;
import static com.antest1.kcanotify.KcaUtils.joinStr; | holder.label_total_num.setText(item.get("total-num").getAsString());
if (item.has("flag-lv")) {
String flagship_lv = item.get("flag-lv").getAsString();
holder.label_flagship_lv.setText(KcaUtils.format("Lv ".concat(flagship_lv)));
} else {
holder.label_flagship_lv.setText("");
}
JsonArray exp_info = item.getAsJsonArray("exp");
int hq_exp = exp_info.get(0).getAsInt();
int ship_exp = exp_info.get(1).getAsInt();
holder.value_hq_exp.setText(String.valueOf(hq_exp * (is_great_success ? 2 : 1)));
holder.value_ship_exp.setText(String.valueOf(ship_exp * (is_great_success ? 2 : 1)));
JsonArray resource = item.getAsJsonArray("resource");
int fuel = resource.get(0).getAsInt();
int ammo = resource.get(1).getAsInt();
int steel = resource.get(2).getAsInt();
int bauxite = resource.get(3).getAsInt();
holder.value_fuel.setText(String.valueOf(calcResourcesBonus(fuel)));
holder.value_ammo.setText(String.valueOf(calcResourcesBonus(ammo)));
holder.value_steel.setText(String.valueOf(calcResourcesBonus(steel)));
holder.value_bauxite.setText(String.valueOf(calcResourcesBonus(bauxite)));
List<String> resource_str_list = new ArrayList<>();
for(int i = 0; i < resource.size(); i++) {
resource_str_list.add(String.valueOf(calcResourcesBonus(resource.get(i).getAsInt())));
} | // Path: app/src/main/java/com/antest1/kcanotify/KcaApiData.java
// public static JsonObject getExpeditionInfo(int mission_no, String locale) {
// JsonObject data = null;
// int mission_key = mission_no;
// String key = String.valueOf(mission_key);
// if (!kcExpeditionData.has(key)) {
// if (mission_no % 2 == 1) key = "203";
// else key = "204";
// }
// JsonObject rawdata = kcExpeditionData.getAsJsonObject(key);
// data = new JsonParser().parse(rawdata.toString()).getAsJsonObject();
// JsonObject name = data.getAsJsonObject("name");
// if (name.has(locale)) {
// data.addProperty("name", name.get(locale).getAsString());
// } else {
// data.addProperty("name", name.get("en").getAsString());
// }
// return data;
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaApiData.java
// public static String getShipTypeAbbr(int idx) {
// if (kcStypeData != null && idx < kcStypeData.size()) {
// return kcStypeData.get(idx).getAsString();
// } else {
// return "";
// }
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static String joinStr(List<String> list, String delim) {
// String resultStr = "";
// if (list.size() > 0) {
// int i;
// for (i = 0; i < list.size() - 1; i++) {
// resultStr = resultStr.concat(list.get(i));
// resultStr = resultStr.concat(delim);
// }
// resultStr = resultStr.concat(list.get(i));
// }
// return resultStr;
// }
// Path: app/src/main/java/com/antest1/kcanotify/KcaExpeditionTableViewAdpater.java
import android.content.Context;
import androidx.core.content.ContextCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import static com.antest1.kcanotify.KcaApiData.getExpeditionInfo;
import static com.antest1.kcanotify.KcaApiData.getShipTypeAbbr;
import static com.antest1.kcanotify.KcaUtils.joinStr;
holder.label_total_num.setText(item.get("total-num").getAsString());
if (item.has("flag-lv")) {
String flagship_lv = item.get("flag-lv").getAsString();
holder.label_flagship_lv.setText(KcaUtils.format("Lv ".concat(flagship_lv)));
} else {
holder.label_flagship_lv.setText("");
}
JsonArray exp_info = item.getAsJsonArray("exp");
int hq_exp = exp_info.get(0).getAsInt();
int ship_exp = exp_info.get(1).getAsInt();
holder.value_hq_exp.setText(String.valueOf(hq_exp * (is_great_success ? 2 : 1)));
holder.value_ship_exp.setText(String.valueOf(ship_exp * (is_great_success ? 2 : 1)));
JsonArray resource = item.getAsJsonArray("resource");
int fuel = resource.get(0).getAsInt();
int ammo = resource.get(1).getAsInt();
int steel = resource.get(2).getAsInt();
int bauxite = resource.get(3).getAsInt();
holder.value_fuel.setText(String.valueOf(calcResourcesBonus(fuel)));
holder.value_ammo.setText(String.valueOf(calcResourcesBonus(ammo)));
holder.value_steel.setText(String.valueOf(calcResourcesBonus(steel)));
holder.value_bauxite.setText(String.valueOf(calcResourcesBonus(bauxite)));
List<String> resource_str_list = new ArrayList<>();
for(int i = 0; i < resource.size(); i++) {
resource_str_list.add(String.valueOf(calcResourcesBonus(resource.get(i).getAsInt())));
} | holder.value_resources_abs.setText(joinStr(resource_str_list, "/")); |
antest1/kcanotify | app/src/main/java/com/antest1/kcanotify/KcaExpeditionTableViewAdpater.java | // Path: app/src/main/java/com/antest1/kcanotify/KcaApiData.java
// public static JsonObject getExpeditionInfo(int mission_no, String locale) {
// JsonObject data = null;
// int mission_key = mission_no;
// String key = String.valueOf(mission_key);
// if (!kcExpeditionData.has(key)) {
// if (mission_no % 2 == 1) key = "203";
// else key = "204";
// }
// JsonObject rawdata = kcExpeditionData.getAsJsonObject(key);
// data = new JsonParser().parse(rawdata.toString()).getAsJsonObject();
// JsonObject name = data.getAsJsonObject("name");
// if (name.has(locale)) {
// data.addProperty("name", name.get(locale).getAsString());
// } else {
// data.addProperty("name", name.get("en").getAsString());
// }
// return data;
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaApiData.java
// public static String getShipTypeAbbr(int idx) {
// if (kcStypeData != null && idx < kcStypeData.size()) {
// return kcStypeData.get(idx).getAsString();
// } else {
// return "";
// }
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static String joinStr(List<String> list, String delim) {
// String resultStr = "";
// if (list.size() > 0) {
// int i;
// for (i = 0; i < list.size() - 1; i++) {
// resultStr = resultStr.concat(list.get(i));
// resultStr = resultStr.concat(delim);
// }
// resultStr = resultStr.concat(list.get(i));
// }
// return resultStr;
// }
| import android.content.Context;
import androidx.core.content.ContextCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import static com.antest1.kcanotify.KcaApiData.getExpeditionInfo;
import static com.antest1.kcanotify.KcaApiData.getShipTypeAbbr;
import static com.antest1.kcanotify.KcaUtils.joinStr; | JsonArray reward2 = reward.get(1).getAsJsonArray();
setRewardData(holder.value_spitem1_type, reward1.get(0).getAsInt(), holder.value_spitem1_count, reward1.get(1).getAsInt());
setRewardData(holder.value_spitem2_type, reward2.get(0).getAsInt(), holder.value_spitem2_count, reward2.get(1).getAsInt());
setRewardData(holder.value_spitem1_abs, reward1.get(0).getAsInt(), null, 0);
setRewardData(holder.value_spitem2_abs, reward2.get(0).getAsInt(), null, 0);
holder.view_abs.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
view.setVisibility(View.GONE);
active.add(target);
holder.view_full.setVisibility(View.VISIBLE);
}
});
holder.view_full.setVisibility(View.GONE);
holder.view_full.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
view.setVisibility(View.GONE);
active.remove(Integer.valueOf(target));
holder.view_abs.setVisibility(View.VISIBLE);
}
});
holder.value_condition.setTag(target);
v.findViewById(R.id.expedition_item_abstract).setVisibility(active.contains(target) ? View.GONE : View.VISIBLE);
v.findViewById(R.id.expedition_item_full).setVisibility(active.contains(target) ? View.VISIBLE : View.GONE);
| // Path: app/src/main/java/com/antest1/kcanotify/KcaApiData.java
// public static JsonObject getExpeditionInfo(int mission_no, String locale) {
// JsonObject data = null;
// int mission_key = mission_no;
// String key = String.valueOf(mission_key);
// if (!kcExpeditionData.has(key)) {
// if (mission_no % 2 == 1) key = "203";
// else key = "204";
// }
// JsonObject rawdata = kcExpeditionData.getAsJsonObject(key);
// data = new JsonParser().parse(rawdata.toString()).getAsJsonObject();
// JsonObject name = data.getAsJsonObject("name");
// if (name.has(locale)) {
// data.addProperty("name", name.get(locale).getAsString());
// } else {
// data.addProperty("name", name.get("en").getAsString());
// }
// return data;
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaApiData.java
// public static String getShipTypeAbbr(int idx) {
// if (kcStypeData != null && idx < kcStypeData.size()) {
// return kcStypeData.get(idx).getAsString();
// } else {
// return "";
// }
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static String joinStr(List<String> list, String delim) {
// String resultStr = "";
// if (list.size() > 0) {
// int i;
// for (i = 0; i < list.size() - 1; i++) {
// resultStr = resultStr.concat(list.get(i));
// resultStr = resultStr.concat(delim);
// }
// resultStr = resultStr.concat(list.get(i));
// }
// return resultStr;
// }
// Path: app/src/main/java/com/antest1/kcanotify/KcaExpeditionTableViewAdpater.java
import android.content.Context;
import androidx.core.content.ContextCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import static com.antest1.kcanotify.KcaApiData.getExpeditionInfo;
import static com.antest1.kcanotify.KcaApiData.getShipTypeAbbr;
import static com.antest1.kcanotify.KcaUtils.joinStr;
JsonArray reward2 = reward.get(1).getAsJsonArray();
setRewardData(holder.value_spitem1_type, reward1.get(0).getAsInt(), holder.value_spitem1_count, reward1.get(1).getAsInt());
setRewardData(holder.value_spitem2_type, reward2.get(0).getAsInt(), holder.value_spitem2_count, reward2.get(1).getAsInt());
setRewardData(holder.value_spitem1_abs, reward1.get(0).getAsInt(), null, 0);
setRewardData(holder.value_spitem2_abs, reward2.get(0).getAsInt(), null, 0);
holder.view_abs.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
view.setVisibility(View.GONE);
active.add(target);
holder.view_full.setVisibility(View.VISIBLE);
}
});
holder.view_full.setVisibility(View.GONE);
holder.view_full.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
view.setVisibility(View.GONE);
active.remove(Integer.valueOf(target));
holder.view_abs.setVisibility(View.VISIBLE);
}
});
holder.value_condition.setTag(target);
v.findViewById(R.id.expedition_item_abstract).setVisibility(active.contains(target) ? View.GONE : View.VISIBLE);
v.findViewById(R.id.expedition_item_full).setVisibility(active.contains(target) ? View.VISIBLE : View.GONE);
| setConditionContent(v.findViewWithTag(target), getExpeditionInfo(target, locale)); |
antest1/kcanotify | app/src/main/java/com/antest1/kcanotify/KcaExpeditionTableViewAdpater.java | // Path: app/src/main/java/com/antest1/kcanotify/KcaApiData.java
// public static JsonObject getExpeditionInfo(int mission_no, String locale) {
// JsonObject data = null;
// int mission_key = mission_no;
// String key = String.valueOf(mission_key);
// if (!kcExpeditionData.has(key)) {
// if (mission_no % 2 == 1) key = "203";
// else key = "204";
// }
// JsonObject rawdata = kcExpeditionData.getAsJsonObject(key);
// data = new JsonParser().parse(rawdata.toString()).getAsJsonObject();
// JsonObject name = data.getAsJsonObject("name");
// if (name.has(locale)) {
// data.addProperty("name", name.get(locale).getAsString());
// } else {
// data.addProperty("name", name.get("en").getAsString());
// }
// return data;
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaApiData.java
// public static String getShipTypeAbbr(int idx) {
// if (kcStypeData != null && idx < kcStypeData.size()) {
// return kcStypeData.get(idx).getAsString();
// } else {
// return "";
// }
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static String joinStr(List<String> list, String delim) {
// String resultStr = "";
// if (list.size() > 0) {
// int i;
// for (i = 0; i < list.size() - 1; i++) {
// resultStr = resultStr.concat(list.get(i));
// resultStr = resultStr.concat(delim);
// }
// resultStr = resultStr.concat(list.get(i));
// }
// return resultStr;
// }
| import android.content.Context;
import androidx.core.content.ContextCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import static com.antest1.kcanotify.KcaApiData.getExpeditionInfo;
import static com.antest1.kcanotify.KcaApiData.getShipTypeAbbr;
import static com.antest1.kcanotify.KcaUtils.joinStr; | boolean has_flag_lv = data.has("flag-lv");
boolean has_flag_cond = data.has("flag-cond");
boolean has_flag_info = has_flag_lv || has_flag_cond;
boolean has_total_lv = data.has("total-lv");
boolean has_total_cond = data.has("total-cond");
boolean has_drum_ship = data.has("drum-ship");
boolean has_drum_num = data.has("drum-num");
boolean has_drum_num_optional = data.has("drum-num-optional");
boolean has_drum_info = has_drum_ship || has_drum_num || has_drum_num_optional;
boolean has_total_asw = data.has("total-asw");
boolean has_total_fp = data.has("total-fp");
boolean has_total_los = data.has("total-los");
boolean has_total_firepower = data.has("total-firepower");
((TextView) root_view.findViewById(R.id.view_excheck_fleet_total_num))
.setText(KcaUtils.format(getStringWithLocale(R.string.excheckview_total_num_format), total_num));
setItemViewVisibilityById(root_view, R.id.view_excheck_flagship, has_flag_info);
if (has_flag_info) {
setItemViewVisibilityById(root_view, R.id.view_excheck_flagship_lv, has_flag_lv);
if (has_flag_lv) {
int flag_lv = data.get("flag-lv").getAsInt();
setItemTextViewById(root_view, R.id.view_excheck_flagship_lv,
KcaUtils.format(getStringWithLocale(R.string.excheckview_flag_lv_format), flag_lv));
}
setItemViewVisibilityById(root_view, R.id.view_excheck_flagship_cond, has_flag_cond);
if (has_flag_cond) {
String[] flag_cond = data.get("flag-cond").getAsString().split("/");
List<String> abbr_text_list = new ArrayList<>();
for (int i = 0; i < flag_cond.length; i++) { | // Path: app/src/main/java/com/antest1/kcanotify/KcaApiData.java
// public static JsonObject getExpeditionInfo(int mission_no, String locale) {
// JsonObject data = null;
// int mission_key = mission_no;
// String key = String.valueOf(mission_key);
// if (!kcExpeditionData.has(key)) {
// if (mission_no % 2 == 1) key = "203";
// else key = "204";
// }
// JsonObject rawdata = kcExpeditionData.getAsJsonObject(key);
// data = new JsonParser().parse(rawdata.toString()).getAsJsonObject();
// JsonObject name = data.getAsJsonObject("name");
// if (name.has(locale)) {
// data.addProperty("name", name.get(locale).getAsString());
// } else {
// data.addProperty("name", name.get("en").getAsString());
// }
// return data;
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaApiData.java
// public static String getShipTypeAbbr(int idx) {
// if (kcStypeData != null && idx < kcStypeData.size()) {
// return kcStypeData.get(idx).getAsString();
// } else {
// return "";
// }
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static String joinStr(List<String> list, String delim) {
// String resultStr = "";
// if (list.size() > 0) {
// int i;
// for (i = 0; i < list.size() - 1; i++) {
// resultStr = resultStr.concat(list.get(i));
// resultStr = resultStr.concat(delim);
// }
// resultStr = resultStr.concat(list.get(i));
// }
// return resultStr;
// }
// Path: app/src/main/java/com/antest1/kcanotify/KcaExpeditionTableViewAdpater.java
import android.content.Context;
import androidx.core.content.ContextCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import static com.antest1.kcanotify.KcaApiData.getExpeditionInfo;
import static com.antest1.kcanotify.KcaApiData.getShipTypeAbbr;
import static com.antest1.kcanotify.KcaUtils.joinStr;
boolean has_flag_lv = data.has("flag-lv");
boolean has_flag_cond = data.has("flag-cond");
boolean has_flag_info = has_flag_lv || has_flag_cond;
boolean has_total_lv = data.has("total-lv");
boolean has_total_cond = data.has("total-cond");
boolean has_drum_ship = data.has("drum-ship");
boolean has_drum_num = data.has("drum-num");
boolean has_drum_num_optional = data.has("drum-num-optional");
boolean has_drum_info = has_drum_ship || has_drum_num || has_drum_num_optional;
boolean has_total_asw = data.has("total-asw");
boolean has_total_fp = data.has("total-fp");
boolean has_total_los = data.has("total-los");
boolean has_total_firepower = data.has("total-firepower");
((TextView) root_view.findViewById(R.id.view_excheck_fleet_total_num))
.setText(KcaUtils.format(getStringWithLocale(R.string.excheckview_total_num_format), total_num));
setItemViewVisibilityById(root_view, R.id.view_excheck_flagship, has_flag_info);
if (has_flag_info) {
setItemViewVisibilityById(root_view, R.id.view_excheck_flagship_lv, has_flag_lv);
if (has_flag_lv) {
int flag_lv = data.get("flag-lv").getAsInt();
setItemTextViewById(root_view, R.id.view_excheck_flagship_lv,
KcaUtils.format(getStringWithLocale(R.string.excheckview_flag_lv_format), flag_lv));
}
setItemViewVisibilityById(root_view, R.id.view_excheck_flagship_cond, has_flag_cond);
if (has_flag_cond) {
String[] flag_cond = data.get("flag-cond").getAsString().split("/");
List<String> abbr_text_list = new ArrayList<>();
for (int i = 0; i < flag_cond.length; i++) { | abbr_text_list.add(getShipTypeAbbr(Integer.parseInt(flag_cond[i]))); |
antest1/kcanotify | app/src/main/java/com/antest1/kcanotify/AkashiFilterActivity.java | // Path: app/src/main/java/com/antest1/kcanotify/KcaApiData.java
// public static final int[] T3LIST_IMPROVABLE = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 19, 20, 21, 23, 24, 30, 31, 34, 36, 37, 38, 42, 43, 44, 46};
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String PREF_AKASHI_FILTERLIST = "akashi_filterlist";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String PREF_KCA_LANGUAGE = "kca_language";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static int getId(String resourceName, Class<?> c) {
// try {
// Field idField = c.getDeclaredField(resourceName);
// return idField.getInt(idField);
// } catch (Exception e) {
// throw new RuntimeException("No resource ID found for: "
// + resourceName + " / " + c, e);
// }
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static String getStringPreferences(Context ctx, String key) {
// SharedPreferences pref = ctx.getSharedPreferences("pref", Context.MODE_PRIVATE);
// try {
// return String.valueOf(pref.getInt(key, 0));
// } catch (Exception e) {
// // Nothing to do
// }
// return pref.getString(key, "");
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static String joinStr(List<String> list, String delim) {
// String resultStr = "";
// if (list.size() > 0) {
// int i;
// for (i = 0; i < list.size() - 1; i++) {
// resultStr = resultStr.concat(list.get(i));
// resultStr = resultStr.concat(delim);
// }
// resultStr = resultStr.concat(list.get(i));
// }
// return resultStr;
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static void setPreferences(Context ctx, String key, Object value) {
// SharedPreferences pref = ctx.getSharedPreferences("pref", Context.MODE_PRIVATE);
// SharedPreferences.Editor editor = pref.edit();
// if (value instanceof String) {
// editor.putString(key, (String) value);
// } else if (value instanceof Boolean) {
// editor.putBoolean(key, (Boolean) value);
// } else if (value instanceof Integer) {
// editor.putString(key, String.valueOf(value));
// } else {
// editor.putString(key, value.toString());
// }
// editor.commit();
// }
| import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import androidx.core.content.ContextCompat;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import static com.antest1.kcanotify.KcaApiData.T3LIST_IMPROVABLE;
import static com.antest1.kcanotify.KcaConstants.PREF_AKASHI_FILTERLIST;
import static com.antest1.kcanotify.KcaConstants.PREF_KCA_LANGUAGE;
import static com.antest1.kcanotify.KcaUtils.getId;
import static com.antest1.kcanotify.KcaUtils.getStringPreferences;
import static com.antest1.kcanotify.KcaUtils.joinStr;
import static com.antest1.kcanotify.KcaUtils.setPreferences; | package com.antest1.kcanotify;
public class AkashiFilterActivity extends AppCompatActivity {
Toolbar toolbar;
private static Handler sHandler;
static Gson gson = new Gson();
TextView itemNameTextView, itemImproveDefaultShipTextView;
Button selectAllButton, selectNoneButton, selectReverseButton;
JsonObject itemImprovementData;
public static void setHandler(Handler h) {
sHandler = h;
}
public AkashiFilterActivity() {
LocaleUtils.updateConfig(this);
}
private String getStringWithLocale(int id) {
return KcaUtils.getStringWithLocale(getApplicationContext(), getBaseContext(), id);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_akashi_filter);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(getResources().getString(R.string.action_akashi_filter));
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
| // Path: app/src/main/java/com/antest1/kcanotify/KcaApiData.java
// public static final int[] T3LIST_IMPROVABLE = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 19, 20, 21, 23, 24, 30, 31, 34, 36, 37, 38, 42, 43, 44, 46};
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String PREF_AKASHI_FILTERLIST = "akashi_filterlist";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String PREF_KCA_LANGUAGE = "kca_language";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static int getId(String resourceName, Class<?> c) {
// try {
// Field idField = c.getDeclaredField(resourceName);
// return idField.getInt(idField);
// } catch (Exception e) {
// throw new RuntimeException("No resource ID found for: "
// + resourceName + " / " + c, e);
// }
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static String getStringPreferences(Context ctx, String key) {
// SharedPreferences pref = ctx.getSharedPreferences("pref", Context.MODE_PRIVATE);
// try {
// return String.valueOf(pref.getInt(key, 0));
// } catch (Exception e) {
// // Nothing to do
// }
// return pref.getString(key, "");
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static String joinStr(List<String> list, String delim) {
// String resultStr = "";
// if (list.size() > 0) {
// int i;
// for (i = 0; i < list.size() - 1; i++) {
// resultStr = resultStr.concat(list.get(i));
// resultStr = resultStr.concat(delim);
// }
// resultStr = resultStr.concat(list.get(i));
// }
// return resultStr;
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static void setPreferences(Context ctx, String key, Object value) {
// SharedPreferences pref = ctx.getSharedPreferences("pref", Context.MODE_PRIVATE);
// SharedPreferences.Editor editor = pref.edit();
// if (value instanceof String) {
// editor.putString(key, (String) value);
// } else if (value instanceof Boolean) {
// editor.putBoolean(key, (Boolean) value);
// } else if (value instanceof Integer) {
// editor.putString(key, String.valueOf(value));
// } else {
// editor.putString(key, value.toString());
// }
// editor.commit();
// }
// Path: app/src/main/java/com/antest1/kcanotify/AkashiFilterActivity.java
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import androidx.core.content.ContextCompat;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import static com.antest1.kcanotify.KcaApiData.T3LIST_IMPROVABLE;
import static com.antest1.kcanotify.KcaConstants.PREF_AKASHI_FILTERLIST;
import static com.antest1.kcanotify.KcaConstants.PREF_KCA_LANGUAGE;
import static com.antest1.kcanotify.KcaUtils.getId;
import static com.antest1.kcanotify.KcaUtils.getStringPreferences;
import static com.antest1.kcanotify.KcaUtils.joinStr;
import static com.antest1.kcanotify.KcaUtils.setPreferences;
package com.antest1.kcanotify;
public class AkashiFilterActivity extends AppCompatActivity {
Toolbar toolbar;
private static Handler sHandler;
static Gson gson = new Gson();
TextView itemNameTextView, itemImproveDefaultShipTextView;
Button selectAllButton, selectNoneButton, selectReverseButton;
JsonObject itemImprovementData;
public static void setHandler(Handler h) {
sHandler = h;
}
public AkashiFilterActivity() {
LocaleUtils.updateConfig(this);
}
private String getStringWithLocale(int id) {
return KcaUtils.getStringWithLocale(getApplicationContext(), getBaseContext(), id);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_akashi_filter);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(getResources().getString(R.string.action_akashi_filter));
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
| final String filter = getStringPreferences(getApplicationContext(), PREF_AKASHI_FILTERLIST); |
antest1/kcanotify | app/src/main/java/com/antest1/kcanotify/AkashiFilterActivity.java | // Path: app/src/main/java/com/antest1/kcanotify/KcaApiData.java
// public static final int[] T3LIST_IMPROVABLE = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 19, 20, 21, 23, 24, 30, 31, 34, 36, 37, 38, 42, 43, 44, 46};
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String PREF_AKASHI_FILTERLIST = "akashi_filterlist";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String PREF_KCA_LANGUAGE = "kca_language";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static int getId(String resourceName, Class<?> c) {
// try {
// Field idField = c.getDeclaredField(resourceName);
// return idField.getInt(idField);
// } catch (Exception e) {
// throw new RuntimeException("No resource ID found for: "
// + resourceName + " / " + c, e);
// }
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static String getStringPreferences(Context ctx, String key) {
// SharedPreferences pref = ctx.getSharedPreferences("pref", Context.MODE_PRIVATE);
// try {
// return String.valueOf(pref.getInt(key, 0));
// } catch (Exception e) {
// // Nothing to do
// }
// return pref.getString(key, "");
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static String joinStr(List<String> list, String delim) {
// String resultStr = "";
// if (list.size() > 0) {
// int i;
// for (i = 0; i < list.size() - 1; i++) {
// resultStr = resultStr.concat(list.get(i));
// resultStr = resultStr.concat(delim);
// }
// resultStr = resultStr.concat(list.get(i));
// }
// return resultStr;
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static void setPreferences(Context ctx, String key, Object value) {
// SharedPreferences pref = ctx.getSharedPreferences("pref", Context.MODE_PRIVATE);
// SharedPreferences.Editor editor = pref.edit();
// if (value instanceof String) {
// editor.putString(key, (String) value);
// } else if (value instanceof Boolean) {
// editor.putBoolean(key, (Boolean) value);
// } else if (value instanceof Integer) {
// editor.putString(key, String.valueOf(value));
// } else {
// editor.putString(key, value.toString());
// }
// editor.commit();
// }
| import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import androidx.core.content.ContextCompat;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import static com.antest1.kcanotify.KcaApiData.T3LIST_IMPROVABLE;
import static com.antest1.kcanotify.KcaConstants.PREF_AKASHI_FILTERLIST;
import static com.antest1.kcanotify.KcaConstants.PREF_KCA_LANGUAGE;
import static com.antest1.kcanotify.KcaUtils.getId;
import static com.antest1.kcanotify.KcaUtils.getStringPreferences;
import static com.antest1.kcanotify.KcaUtils.joinStr;
import static com.antest1.kcanotify.KcaUtils.setPreferences; | package com.antest1.kcanotify;
public class AkashiFilterActivity extends AppCompatActivity {
Toolbar toolbar;
private static Handler sHandler;
static Gson gson = new Gson();
TextView itemNameTextView, itemImproveDefaultShipTextView;
Button selectAllButton, selectNoneButton, selectReverseButton;
JsonObject itemImprovementData;
public static void setHandler(Handler h) {
sHandler = h;
}
public AkashiFilterActivity() {
LocaleUtils.updateConfig(this);
}
private String getStringWithLocale(int id) {
return KcaUtils.getStringWithLocale(getApplicationContext(), getBaseContext(), id);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_akashi_filter);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(getResources().getString(R.string.action_akashi_filter));
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
| // Path: app/src/main/java/com/antest1/kcanotify/KcaApiData.java
// public static final int[] T3LIST_IMPROVABLE = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 19, 20, 21, 23, 24, 30, 31, 34, 36, 37, 38, 42, 43, 44, 46};
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String PREF_AKASHI_FILTERLIST = "akashi_filterlist";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String PREF_KCA_LANGUAGE = "kca_language";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static int getId(String resourceName, Class<?> c) {
// try {
// Field idField = c.getDeclaredField(resourceName);
// return idField.getInt(idField);
// } catch (Exception e) {
// throw new RuntimeException("No resource ID found for: "
// + resourceName + " / " + c, e);
// }
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static String getStringPreferences(Context ctx, String key) {
// SharedPreferences pref = ctx.getSharedPreferences("pref", Context.MODE_PRIVATE);
// try {
// return String.valueOf(pref.getInt(key, 0));
// } catch (Exception e) {
// // Nothing to do
// }
// return pref.getString(key, "");
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static String joinStr(List<String> list, String delim) {
// String resultStr = "";
// if (list.size() > 0) {
// int i;
// for (i = 0; i < list.size() - 1; i++) {
// resultStr = resultStr.concat(list.get(i));
// resultStr = resultStr.concat(delim);
// }
// resultStr = resultStr.concat(list.get(i));
// }
// return resultStr;
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static void setPreferences(Context ctx, String key, Object value) {
// SharedPreferences pref = ctx.getSharedPreferences("pref", Context.MODE_PRIVATE);
// SharedPreferences.Editor editor = pref.edit();
// if (value instanceof String) {
// editor.putString(key, (String) value);
// } else if (value instanceof Boolean) {
// editor.putBoolean(key, (Boolean) value);
// } else if (value instanceof Integer) {
// editor.putString(key, String.valueOf(value));
// } else {
// editor.putString(key, value.toString());
// }
// editor.commit();
// }
// Path: app/src/main/java/com/antest1/kcanotify/AkashiFilterActivity.java
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import androidx.core.content.ContextCompat;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import static com.antest1.kcanotify.KcaApiData.T3LIST_IMPROVABLE;
import static com.antest1.kcanotify.KcaConstants.PREF_AKASHI_FILTERLIST;
import static com.antest1.kcanotify.KcaConstants.PREF_KCA_LANGUAGE;
import static com.antest1.kcanotify.KcaUtils.getId;
import static com.antest1.kcanotify.KcaUtils.getStringPreferences;
import static com.antest1.kcanotify.KcaUtils.joinStr;
import static com.antest1.kcanotify.KcaUtils.setPreferences;
package com.antest1.kcanotify;
public class AkashiFilterActivity extends AppCompatActivity {
Toolbar toolbar;
private static Handler sHandler;
static Gson gson = new Gson();
TextView itemNameTextView, itemImproveDefaultShipTextView;
Button selectAllButton, selectNoneButton, selectReverseButton;
JsonObject itemImprovementData;
public static void setHandler(Handler h) {
sHandler = h;
}
public AkashiFilterActivity() {
LocaleUtils.updateConfig(this);
}
private String getStringWithLocale(int id) {
return KcaUtils.getStringWithLocale(getApplicationContext(), getBaseContext(), id);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_akashi_filter);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(getResources().getString(R.string.action_akashi_filter));
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
| final String filter = getStringPreferences(getApplicationContext(), PREF_AKASHI_FILTERLIST); |
antest1/kcanotify | app/src/main/java/com/antest1/kcanotify/AkashiFilterActivity.java | // Path: app/src/main/java/com/antest1/kcanotify/KcaApiData.java
// public static final int[] T3LIST_IMPROVABLE = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 19, 20, 21, 23, 24, 30, 31, 34, 36, 37, 38, 42, 43, 44, 46};
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String PREF_AKASHI_FILTERLIST = "akashi_filterlist";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String PREF_KCA_LANGUAGE = "kca_language";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static int getId(String resourceName, Class<?> c) {
// try {
// Field idField = c.getDeclaredField(resourceName);
// return idField.getInt(idField);
// } catch (Exception e) {
// throw new RuntimeException("No resource ID found for: "
// + resourceName + " / " + c, e);
// }
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static String getStringPreferences(Context ctx, String key) {
// SharedPreferences pref = ctx.getSharedPreferences("pref", Context.MODE_PRIVATE);
// try {
// return String.valueOf(pref.getInt(key, 0));
// } catch (Exception e) {
// // Nothing to do
// }
// return pref.getString(key, "");
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static String joinStr(List<String> list, String delim) {
// String resultStr = "";
// if (list.size() > 0) {
// int i;
// for (i = 0; i < list.size() - 1; i++) {
// resultStr = resultStr.concat(list.get(i));
// resultStr = resultStr.concat(delim);
// }
// resultStr = resultStr.concat(list.get(i));
// }
// return resultStr;
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static void setPreferences(Context ctx, String key, Object value) {
// SharedPreferences pref = ctx.getSharedPreferences("pref", Context.MODE_PRIVATE);
// SharedPreferences.Editor editor = pref.edit();
// if (value instanceof String) {
// editor.putString(key, (String) value);
// } else if (value instanceof Boolean) {
// editor.putBoolean(key, (Boolean) value);
// } else if (value instanceof Integer) {
// editor.putString(key, String.valueOf(value));
// } else {
// editor.putString(key, value.toString());
// }
// editor.commit();
// }
| import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import androidx.core.content.ContextCompat;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import static com.antest1.kcanotify.KcaApiData.T3LIST_IMPROVABLE;
import static com.antest1.kcanotify.KcaConstants.PREF_AKASHI_FILTERLIST;
import static com.antest1.kcanotify.KcaConstants.PREF_KCA_LANGUAGE;
import static com.antest1.kcanotify.KcaUtils.getId;
import static com.antest1.kcanotify.KcaUtils.getStringPreferences;
import static com.antest1.kcanotify.KcaUtils.joinStr;
import static com.antest1.kcanotify.KcaUtils.setPreferences; | package com.antest1.kcanotify;
public class AkashiFilterActivity extends AppCompatActivity {
Toolbar toolbar;
private static Handler sHandler;
static Gson gson = new Gson();
TextView itemNameTextView, itemImproveDefaultShipTextView;
Button selectAllButton, selectNoneButton, selectReverseButton;
JsonObject itemImprovementData;
public static void setHandler(Handler h) {
sHandler = h;
}
public AkashiFilterActivity() {
LocaleUtils.updateConfig(this);
}
private String getStringWithLocale(int id) {
return KcaUtils.getStringWithLocale(getApplicationContext(), getBaseContext(), id);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_akashi_filter);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(getResources().getString(R.string.action_akashi_filter));
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
final String filter = getStringPreferences(getApplicationContext(), PREF_AKASHI_FILTERLIST); | // Path: app/src/main/java/com/antest1/kcanotify/KcaApiData.java
// public static final int[] T3LIST_IMPROVABLE = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 19, 20, 21, 23, 24, 30, 31, 34, 36, 37, 38, 42, 43, 44, 46};
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String PREF_AKASHI_FILTERLIST = "akashi_filterlist";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String PREF_KCA_LANGUAGE = "kca_language";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static int getId(String resourceName, Class<?> c) {
// try {
// Field idField = c.getDeclaredField(resourceName);
// return idField.getInt(idField);
// } catch (Exception e) {
// throw new RuntimeException("No resource ID found for: "
// + resourceName + " / " + c, e);
// }
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static String getStringPreferences(Context ctx, String key) {
// SharedPreferences pref = ctx.getSharedPreferences("pref", Context.MODE_PRIVATE);
// try {
// return String.valueOf(pref.getInt(key, 0));
// } catch (Exception e) {
// // Nothing to do
// }
// return pref.getString(key, "");
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static String joinStr(List<String> list, String delim) {
// String resultStr = "";
// if (list.size() > 0) {
// int i;
// for (i = 0; i < list.size() - 1; i++) {
// resultStr = resultStr.concat(list.get(i));
// resultStr = resultStr.concat(delim);
// }
// resultStr = resultStr.concat(list.get(i));
// }
// return resultStr;
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static void setPreferences(Context ctx, String key, Object value) {
// SharedPreferences pref = ctx.getSharedPreferences("pref", Context.MODE_PRIVATE);
// SharedPreferences.Editor editor = pref.edit();
// if (value instanceof String) {
// editor.putString(key, (String) value);
// } else if (value instanceof Boolean) {
// editor.putBoolean(key, (Boolean) value);
// } else if (value instanceof Integer) {
// editor.putString(key, String.valueOf(value));
// } else {
// editor.putString(key, value.toString());
// }
// editor.commit();
// }
// Path: app/src/main/java/com/antest1/kcanotify/AkashiFilterActivity.java
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import androidx.core.content.ContextCompat;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import static com.antest1.kcanotify.KcaApiData.T3LIST_IMPROVABLE;
import static com.antest1.kcanotify.KcaConstants.PREF_AKASHI_FILTERLIST;
import static com.antest1.kcanotify.KcaConstants.PREF_KCA_LANGUAGE;
import static com.antest1.kcanotify.KcaUtils.getId;
import static com.antest1.kcanotify.KcaUtils.getStringPreferences;
import static com.antest1.kcanotify.KcaUtils.joinStr;
import static com.antest1.kcanotify.KcaUtils.setPreferences;
package com.antest1.kcanotify;
public class AkashiFilterActivity extends AppCompatActivity {
Toolbar toolbar;
private static Handler sHandler;
static Gson gson = new Gson();
TextView itemNameTextView, itemImproveDefaultShipTextView;
Button selectAllButton, selectNoneButton, selectReverseButton;
JsonObject itemImprovementData;
public static void setHandler(Handler h) {
sHandler = h;
}
public AkashiFilterActivity() {
LocaleUtils.updateConfig(this);
}
private String getStringWithLocale(int id) {
return KcaUtils.getStringWithLocale(getApplicationContext(), getBaseContext(), id);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_akashi_filter);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(getResources().getString(R.string.action_akashi_filter));
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
final String filter = getStringPreferences(getApplicationContext(), PREF_AKASHI_FILTERLIST); | for(final int type: T3LIST_IMPROVABLE) { |
antest1/kcanotify | app/src/main/java/com/antest1/kcanotify/AkashiFilterActivity.java | // Path: app/src/main/java/com/antest1/kcanotify/KcaApiData.java
// public static final int[] T3LIST_IMPROVABLE = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 19, 20, 21, 23, 24, 30, 31, 34, 36, 37, 38, 42, 43, 44, 46};
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String PREF_AKASHI_FILTERLIST = "akashi_filterlist";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String PREF_KCA_LANGUAGE = "kca_language";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static int getId(String resourceName, Class<?> c) {
// try {
// Field idField = c.getDeclaredField(resourceName);
// return idField.getInt(idField);
// } catch (Exception e) {
// throw new RuntimeException("No resource ID found for: "
// + resourceName + " / " + c, e);
// }
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static String getStringPreferences(Context ctx, String key) {
// SharedPreferences pref = ctx.getSharedPreferences("pref", Context.MODE_PRIVATE);
// try {
// return String.valueOf(pref.getInt(key, 0));
// } catch (Exception e) {
// // Nothing to do
// }
// return pref.getString(key, "");
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static String joinStr(List<String> list, String delim) {
// String resultStr = "";
// if (list.size() > 0) {
// int i;
// for (i = 0; i < list.size() - 1; i++) {
// resultStr = resultStr.concat(list.get(i));
// resultStr = resultStr.concat(delim);
// }
// resultStr = resultStr.concat(list.get(i));
// }
// return resultStr;
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static void setPreferences(Context ctx, String key, Object value) {
// SharedPreferences pref = ctx.getSharedPreferences("pref", Context.MODE_PRIVATE);
// SharedPreferences.Editor editor = pref.edit();
// if (value instanceof String) {
// editor.putString(key, (String) value);
// } else if (value instanceof Boolean) {
// editor.putBoolean(key, (Boolean) value);
// } else if (value instanceof Integer) {
// editor.putString(key, String.valueOf(value));
// } else {
// editor.putString(key, value.toString());
// }
// editor.commit();
// }
| import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import androidx.core.content.ContextCompat;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import static com.antest1.kcanotify.KcaApiData.T3LIST_IMPROVABLE;
import static com.antest1.kcanotify.KcaConstants.PREF_AKASHI_FILTERLIST;
import static com.antest1.kcanotify.KcaConstants.PREF_KCA_LANGUAGE;
import static com.antest1.kcanotify.KcaUtils.getId;
import static com.antest1.kcanotify.KcaUtils.getStringPreferences;
import static com.antest1.kcanotify.KcaUtils.joinStr;
import static com.antest1.kcanotify.KcaUtils.setPreferences; | package com.antest1.kcanotify;
public class AkashiFilterActivity extends AppCompatActivity {
Toolbar toolbar;
private static Handler sHandler;
static Gson gson = new Gson();
TextView itemNameTextView, itemImproveDefaultShipTextView;
Button selectAllButton, selectNoneButton, selectReverseButton;
JsonObject itemImprovementData;
public static void setHandler(Handler h) {
sHandler = h;
}
public AkashiFilterActivity() {
LocaleUtils.updateConfig(this);
}
private String getStringWithLocale(int id) {
return KcaUtils.getStringWithLocale(getApplicationContext(), getBaseContext(), id);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_akashi_filter);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(getResources().getString(R.string.action_akashi_filter));
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
final String filter = getStringPreferences(getApplicationContext(), PREF_AKASHI_FILTERLIST);
for(final int type: T3LIST_IMPROVABLE) { | // Path: app/src/main/java/com/antest1/kcanotify/KcaApiData.java
// public static final int[] T3LIST_IMPROVABLE = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 19, 20, 21, 23, 24, 30, 31, 34, 36, 37, 38, 42, 43, 44, 46};
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String PREF_AKASHI_FILTERLIST = "akashi_filterlist";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String PREF_KCA_LANGUAGE = "kca_language";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static int getId(String resourceName, Class<?> c) {
// try {
// Field idField = c.getDeclaredField(resourceName);
// return idField.getInt(idField);
// } catch (Exception e) {
// throw new RuntimeException("No resource ID found for: "
// + resourceName + " / " + c, e);
// }
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static String getStringPreferences(Context ctx, String key) {
// SharedPreferences pref = ctx.getSharedPreferences("pref", Context.MODE_PRIVATE);
// try {
// return String.valueOf(pref.getInt(key, 0));
// } catch (Exception e) {
// // Nothing to do
// }
// return pref.getString(key, "");
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static String joinStr(List<String> list, String delim) {
// String resultStr = "";
// if (list.size() > 0) {
// int i;
// for (i = 0; i < list.size() - 1; i++) {
// resultStr = resultStr.concat(list.get(i));
// resultStr = resultStr.concat(delim);
// }
// resultStr = resultStr.concat(list.get(i));
// }
// return resultStr;
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static void setPreferences(Context ctx, String key, Object value) {
// SharedPreferences pref = ctx.getSharedPreferences("pref", Context.MODE_PRIVATE);
// SharedPreferences.Editor editor = pref.edit();
// if (value instanceof String) {
// editor.putString(key, (String) value);
// } else if (value instanceof Boolean) {
// editor.putBoolean(key, (Boolean) value);
// } else if (value instanceof Integer) {
// editor.putString(key, String.valueOf(value));
// } else {
// editor.putString(key, value.toString());
// }
// editor.commit();
// }
// Path: app/src/main/java/com/antest1/kcanotify/AkashiFilterActivity.java
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import androidx.core.content.ContextCompat;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import static com.antest1.kcanotify.KcaApiData.T3LIST_IMPROVABLE;
import static com.antest1.kcanotify.KcaConstants.PREF_AKASHI_FILTERLIST;
import static com.antest1.kcanotify.KcaConstants.PREF_KCA_LANGUAGE;
import static com.antest1.kcanotify.KcaUtils.getId;
import static com.antest1.kcanotify.KcaUtils.getStringPreferences;
import static com.antest1.kcanotify.KcaUtils.joinStr;
import static com.antest1.kcanotify.KcaUtils.setPreferences;
package com.antest1.kcanotify;
public class AkashiFilterActivity extends AppCompatActivity {
Toolbar toolbar;
private static Handler sHandler;
static Gson gson = new Gson();
TextView itemNameTextView, itemImproveDefaultShipTextView;
Button selectAllButton, selectNoneButton, selectReverseButton;
JsonObject itemImprovementData;
public static void setHandler(Handler h) {
sHandler = h;
}
public AkashiFilterActivity() {
LocaleUtils.updateConfig(this);
}
private String getStringWithLocale(int id) {
return KcaUtils.getStringWithLocale(getApplicationContext(), getBaseContext(), id);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_akashi_filter);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(getResources().getString(R.string.action_akashi_filter));
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
final String filter = getStringPreferences(getApplicationContext(), PREF_AKASHI_FILTERLIST);
for(final int type: T3LIST_IMPROVABLE) { | int btnId = getId("akashi_filter_equip_btn_".concat(String.valueOf(type)), R.id.class); |
antest1/kcanotify | app/src/main/java/com/antest1/kcanotify/AkashiFilterActivity.java | // Path: app/src/main/java/com/antest1/kcanotify/KcaApiData.java
// public static final int[] T3LIST_IMPROVABLE = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 19, 20, 21, 23, 24, 30, 31, 34, 36, 37, 38, 42, 43, 44, 46};
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String PREF_AKASHI_FILTERLIST = "akashi_filterlist";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String PREF_KCA_LANGUAGE = "kca_language";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static int getId(String resourceName, Class<?> c) {
// try {
// Field idField = c.getDeclaredField(resourceName);
// return idField.getInt(idField);
// } catch (Exception e) {
// throw new RuntimeException("No resource ID found for: "
// + resourceName + " / " + c, e);
// }
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static String getStringPreferences(Context ctx, String key) {
// SharedPreferences pref = ctx.getSharedPreferences("pref", Context.MODE_PRIVATE);
// try {
// return String.valueOf(pref.getInt(key, 0));
// } catch (Exception e) {
// // Nothing to do
// }
// return pref.getString(key, "");
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static String joinStr(List<String> list, String delim) {
// String resultStr = "";
// if (list.size() > 0) {
// int i;
// for (i = 0; i < list.size() - 1; i++) {
// resultStr = resultStr.concat(list.get(i));
// resultStr = resultStr.concat(delim);
// }
// resultStr = resultStr.concat(list.get(i));
// }
// return resultStr;
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static void setPreferences(Context ctx, String key, Object value) {
// SharedPreferences pref = ctx.getSharedPreferences("pref", Context.MODE_PRIVATE);
// SharedPreferences.Editor editor = pref.edit();
// if (value instanceof String) {
// editor.putString(key, (String) value);
// } else if (value instanceof Boolean) {
// editor.putBoolean(key, (Boolean) value);
// } else if (value instanceof Integer) {
// editor.putString(key, String.valueOf(value));
// } else {
// editor.putString(key, value.toString());
// }
// editor.commit();
// }
| import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import androidx.core.content.ContextCompat;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import static com.antest1.kcanotify.KcaApiData.T3LIST_IMPROVABLE;
import static com.antest1.kcanotify.KcaConstants.PREF_AKASHI_FILTERLIST;
import static com.antest1.kcanotify.KcaConstants.PREF_KCA_LANGUAGE;
import static com.antest1.kcanotify.KcaUtils.getId;
import static com.antest1.kcanotify.KcaUtils.getStringPreferences;
import static com.antest1.kcanotify.KcaUtils.joinStr;
import static com.antest1.kcanotify.KcaUtils.setPreferences; | public static void setHandler(Handler h) {
sHandler = h;
}
public AkashiFilterActivity() {
LocaleUtils.updateConfig(this);
}
private String getStringWithLocale(int id) {
return KcaUtils.getStringWithLocale(getApplicationContext(), getBaseContext(), id);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_akashi_filter);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(getResources().getString(R.string.action_akashi_filter));
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
final String filter = getStringPreferences(getApplicationContext(), PREF_AKASHI_FILTERLIST);
for(final int type: T3LIST_IMPROVABLE) {
int btnId = getId("akashi_filter_equip_btn_".concat(String.valueOf(type)), R.id.class);
final ImageView btnView = (ImageView) findViewById(btnId);
btnView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String filter = getStringPreferences(getApplicationContext(), PREF_AKASHI_FILTERLIST);
if(checkFiltered(filter, type)) { | // Path: app/src/main/java/com/antest1/kcanotify/KcaApiData.java
// public static final int[] T3LIST_IMPROVABLE = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 19, 20, 21, 23, 24, 30, 31, 34, 36, 37, 38, 42, 43, 44, 46};
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String PREF_AKASHI_FILTERLIST = "akashi_filterlist";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String PREF_KCA_LANGUAGE = "kca_language";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static int getId(String resourceName, Class<?> c) {
// try {
// Field idField = c.getDeclaredField(resourceName);
// return idField.getInt(idField);
// } catch (Exception e) {
// throw new RuntimeException("No resource ID found for: "
// + resourceName + " / " + c, e);
// }
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static String getStringPreferences(Context ctx, String key) {
// SharedPreferences pref = ctx.getSharedPreferences("pref", Context.MODE_PRIVATE);
// try {
// return String.valueOf(pref.getInt(key, 0));
// } catch (Exception e) {
// // Nothing to do
// }
// return pref.getString(key, "");
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static String joinStr(List<String> list, String delim) {
// String resultStr = "";
// if (list.size() > 0) {
// int i;
// for (i = 0; i < list.size() - 1; i++) {
// resultStr = resultStr.concat(list.get(i));
// resultStr = resultStr.concat(delim);
// }
// resultStr = resultStr.concat(list.get(i));
// }
// return resultStr;
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static void setPreferences(Context ctx, String key, Object value) {
// SharedPreferences pref = ctx.getSharedPreferences("pref", Context.MODE_PRIVATE);
// SharedPreferences.Editor editor = pref.edit();
// if (value instanceof String) {
// editor.putString(key, (String) value);
// } else if (value instanceof Boolean) {
// editor.putBoolean(key, (Boolean) value);
// } else if (value instanceof Integer) {
// editor.putString(key, String.valueOf(value));
// } else {
// editor.putString(key, value.toString());
// }
// editor.commit();
// }
// Path: app/src/main/java/com/antest1/kcanotify/AkashiFilterActivity.java
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import androidx.core.content.ContextCompat;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import static com.antest1.kcanotify.KcaApiData.T3LIST_IMPROVABLE;
import static com.antest1.kcanotify.KcaConstants.PREF_AKASHI_FILTERLIST;
import static com.antest1.kcanotify.KcaConstants.PREF_KCA_LANGUAGE;
import static com.antest1.kcanotify.KcaUtils.getId;
import static com.antest1.kcanotify.KcaUtils.getStringPreferences;
import static com.antest1.kcanotify.KcaUtils.joinStr;
import static com.antest1.kcanotify.KcaUtils.setPreferences;
public static void setHandler(Handler h) {
sHandler = h;
}
public AkashiFilterActivity() {
LocaleUtils.updateConfig(this);
}
private String getStringWithLocale(int id) {
return KcaUtils.getStringWithLocale(getApplicationContext(), getBaseContext(), id);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_akashi_filter);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(getResources().getString(R.string.action_akashi_filter));
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
final String filter = getStringPreferences(getApplicationContext(), PREF_AKASHI_FILTERLIST);
for(final int type: T3LIST_IMPROVABLE) {
int btnId = getId("akashi_filter_equip_btn_".concat(String.valueOf(type)), R.id.class);
final ImageView btnView = (ImageView) findViewById(btnId);
btnView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String filter = getStringPreferences(getApplicationContext(), PREF_AKASHI_FILTERLIST);
if(checkFiltered(filter, type)) { | setPreferences(getApplicationContext(), PREF_AKASHI_FILTERLIST, deleteFiltered(filter, type)); |
antest1/kcanotify | app/src/main/java/com/antest1/kcanotify/AkashiFilterActivity.java | // Path: app/src/main/java/com/antest1/kcanotify/KcaApiData.java
// public static final int[] T3LIST_IMPROVABLE = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 19, 20, 21, 23, 24, 30, 31, 34, 36, 37, 38, 42, 43, 44, 46};
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String PREF_AKASHI_FILTERLIST = "akashi_filterlist";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String PREF_KCA_LANGUAGE = "kca_language";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static int getId(String resourceName, Class<?> c) {
// try {
// Field idField = c.getDeclaredField(resourceName);
// return idField.getInt(idField);
// } catch (Exception e) {
// throw new RuntimeException("No resource ID found for: "
// + resourceName + " / " + c, e);
// }
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static String getStringPreferences(Context ctx, String key) {
// SharedPreferences pref = ctx.getSharedPreferences("pref", Context.MODE_PRIVATE);
// try {
// return String.valueOf(pref.getInt(key, 0));
// } catch (Exception e) {
// // Nothing to do
// }
// return pref.getString(key, "");
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static String joinStr(List<String> list, String delim) {
// String resultStr = "";
// if (list.size() > 0) {
// int i;
// for (i = 0; i < list.size() - 1; i++) {
// resultStr = resultStr.concat(list.get(i));
// resultStr = resultStr.concat(delim);
// }
// resultStr = resultStr.concat(list.get(i));
// }
// return resultStr;
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static void setPreferences(Context ctx, String key, Object value) {
// SharedPreferences pref = ctx.getSharedPreferences("pref", Context.MODE_PRIVATE);
// SharedPreferences.Editor editor = pref.edit();
// if (value instanceof String) {
// editor.putString(key, (String) value);
// } else if (value instanceof Boolean) {
// editor.putBoolean(key, (Boolean) value);
// } else if (value instanceof Integer) {
// editor.putString(key, String.valueOf(value));
// } else {
// editor.putString(key, value.toString());
// }
// editor.commit();
// }
| import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import androidx.core.content.ContextCompat;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import static com.antest1.kcanotify.KcaApiData.T3LIST_IMPROVABLE;
import static com.antest1.kcanotify.KcaConstants.PREF_AKASHI_FILTERLIST;
import static com.antest1.kcanotify.KcaConstants.PREF_KCA_LANGUAGE;
import static com.antest1.kcanotify.KcaUtils.getId;
import static com.antest1.kcanotify.KcaUtils.getStringPreferences;
import static com.antest1.kcanotify.KcaUtils.joinStr;
import static com.antest1.kcanotify.KcaUtils.setPreferences; | setPreferences(getApplicationContext(), PREF_AKASHI_FILTERLIST, addFiltered(filter, type));
btnView.setBackground(ContextCompat.getDrawable(getApplicationContext(), R.drawable.imagebtn_off));
}
sHandler.sendEmptyMessage(0);
}
});
}
setEquipButton();
selectAllButton = (Button) findViewById(R.id.akashi_filter_btn_all);
selectNoneButton = (Button) findViewById(R.id.akashi_filter_btn_none);
selectReverseButton = (Button) findViewById(R.id.akashi_filter_btn_reverse);
selectAllButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setPreferences(getApplicationContext(), PREF_AKASHI_FILTERLIST, "|");
setEquipButton();
sHandler.sendEmptyMessage(0);
}
});
selectNoneButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
List<String> typelist = new ArrayList<String>();
for(int type: T3LIST_IMPROVABLE) {
typelist.add(String.valueOf(type));
}
setPreferences(getApplicationContext(), PREF_AKASHI_FILTERLIST, | // Path: app/src/main/java/com/antest1/kcanotify/KcaApiData.java
// public static final int[] T3LIST_IMPROVABLE = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 19, 20, 21, 23, 24, 30, 31, 34, 36, 37, 38, 42, 43, 44, 46};
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String PREF_AKASHI_FILTERLIST = "akashi_filterlist";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String PREF_KCA_LANGUAGE = "kca_language";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static int getId(String resourceName, Class<?> c) {
// try {
// Field idField = c.getDeclaredField(resourceName);
// return idField.getInt(idField);
// } catch (Exception e) {
// throw new RuntimeException("No resource ID found for: "
// + resourceName + " / " + c, e);
// }
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static String getStringPreferences(Context ctx, String key) {
// SharedPreferences pref = ctx.getSharedPreferences("pref", Context.MODE_PRIVATE);
// try {
// return String.valueOf(pref.getInt(key, 0));
// } catch (Exception e) {
// // Nothing to do
// }
// return pref.getString(key, "");
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static String joinStr(List<String> list, String delim) {
// String resultStr = "";
// if (list.size() > 0) {
// int i;
// for (i = 0; i < list.size() - 1; i++) {
// resultStr = resultStr.concat(list.get(i));
// resultStr = resultStr.concat(delim);
// }
// resultStr = resultStr.concat(list.get(i));
// }
// return resultStr;
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static void setPreferences(Context ctx, String key, Object value) {
// SharedPreferences pref = ctx.getSharedPreferences("pref", Context.MODE_PRIVATE);
// SharedPreferences.Editor editor = pref.edit();
// if (value instanceof String) {
// editor.putString(key, (String) value);
// } else if (value instanceof Boolean) {
// editor.putBoolean(key, (Boolean) value);
// } else if (value instanceof Integer) {
// editor.putString(key, String.valueOf(value));
// } else {
// editor.putString(key, value.toString());
// }
// editor.commit();
// }
// Path: app/src/main/java/com/antest1/kcanotify/AkashiFilterActivity.java
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import androidx.core.content.ContextCompat;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import static com.antest1.kcanotify.KcaApiData.T3LIST_IMPROVABLE;
import static com.antest1.kcanotify.KcaConstants.PREF_AKASHI_FILTERLIST;
import static com.antest1.kcanotify.KcaConstants.PREF_KCA_LANGUAGE;
import static com.antest1.kcanotify.KcaUtils.getId;
import static com.antest1.kcanotify.KcaUtils.getStringPreferences;
import static com.antest1.kcanotify.KcaUtils.joinStr;
import static com.antest1.kcanotify.KcaUtils.setPreferences;
setPreferences(getApplicationContext(), PREF_AKASHI_FILTERLIST, addFiltered(filter, type));
btnView.setBackground(ContextCompat.getDrawable(getApplicationContext(), R.drawable.imagebtn_off));
}
sHandler.sendEmptyMessage(0);
}
});
}
setEquipButton();
selectAllButton = (Button) findViewById(R.id.akashi_filter_btn_all);
selectNoneButton = (Button) findViewById(R.id.akashi_filter_btn_none);
selectReverseButton = (Button) findViewById(R.id.akashi_filter_btn_reverse);
selectAllButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setPreferences(getApplicationContext(), PREF_AKASHI_FILTERLIST, "|");
setEquipButton();
sHandler.sendEmptyMessage(0);
}
});
selectNoneButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
List<String> typelist = new ArrayList<String>();
for(int type: T3LIST_IMPROVABLE) {
typelist.add(String.valueOf(type));
}
setPreferences(getApplicationContext(), PREF_AKASHI_FILTERLIST, | "|".concat(joinStr(typelist, "|")).concat("|")); |
antest1/kcanotify | app/src/main/java/com/antest1/kcanotify/AkashiFilterActivity.java | // Path: app/src/main/java/com/antest1/kcanotify/KcaApiData.java
// public static final int[] T3LIST_IMPROVABLE = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 19, 20, 21, 23, 24, 30, 31, 34, 36, 37, 38, 42, 43, 44, 46};
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String PREF_AKASHI_FILTERLIST = "akashi_filterlist";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String PREF_KCA_LANGUAGE = "kca_language";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static int getId(String resourceName, Class<?> c) {
// try {
// Field idField = c.getDeclaredField(resourceName);
// return idField.getInt(idField);
// } catch (Exception e) {
// throw new RuntimeException("No resource ID found for: "
// + resourceName + " / " + c, e);
// }
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static String getStringPreferences(Context ctx, String key) {
// SharedPreferences pref = ctx.getSharedPreferences("pref", Context.MODE_PRIVATE);
// try {
// return String.valueOf(pref.getInt(key, 0));
// } catch (Exception e) {
// // Nothing to do
// }
// return pref.getString(key, "");
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static String joinStr(List<String> list, String delim) {
// String resultStr = "";
// if (list.size() > 0) {
// int i;
// for (i = 0; i < list.size() - 1; i++) {
// resultStr = resultStr.concat(list.get(i));
// resultStr = resultStr.concat(delim);
// }
// resultStr = resultStr.concat(list.get(i));
// }
// return resultStr;
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static void setPreferences(Context ctx, String key, Object value) {
// SharedPreferences pref = ctx.getSharedPreferences("pref", Context.MODE_PRIVATE);
// SharedPreferences.Editor editor = pref.edit();
// if (value instanceof String) {
// editor.putString(key, (String) value);
// } else if (value instanceof Boolean) {
// editor.putBoolean(key, (Boolean) value);
// } else if (value instanceof Integer) {
// editor.putString(key, String.valueOf(value));
// } else {
// editor.putString(key, value.toString());
// }
// editor.commit();
// }
| import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import androidx.core.content.ContextCompat;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import static com.antest1.kcanotify.KcaApiData.T3LIST_IMPROVABLE;
import static com.antest1.kcanotify.KcaConstants.PREF_AKASHI_FILTERLIST;
import static com.antest1.kcanotify.KcaConstants.PREF_KCA_LANGUAGE;
import static com.antest1.kcanotify.KcaUtils.getId;
import static com.antest1.kcanotify.KcaUtils.getStringPreferences;
import static com.antest1.kcanotify.KcaUtils.joinStr;
import static com.antest1.kcanotify.KcaUtils.setPreferences; | private String addFiltered(String data, int id) {
return data.concat(String.valueOf(id)).concat("|");
}
private String deleteFiltered(String data, int id) {
return data.replace(KcaUtils.format("|%d|",id), "|");
}
private void setEquipButton() {
String filter = getStringPreferences(getApplicationContext(), PREF_AKASHI_FILTERLIST);
for(int type: T3LIST_IMPROVABLE) {
int btnId = getId("akashi_filter_equip_btn_".concat(String.valueOf(type)), R.id.class);
ImageView btnView = (ImageView) findViewById(btnId);
if(checkFiltered(filter, type)) {
btnView.setBackground(ContextCompat.getDrawable(this, R.drawable.imagebtn_off));
} else {
btnView.setBackground(ContextCompat.getDrawable(this, R.drawable.imagebtn_on));
}
}
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Log.e("KCA", "lang: " + newConfig.getLocales().get(0).getLanguage() + " " + newConfig.getLocales().get(0).getCountry());
KcaApplication.defaultLocale = newConfig.getLocales().get(0);
} else {
Log.e("KCA", "lang: " + newConfig.locale.getLanguage() + " " + newConfig.locale.getCountry());
KcaApplication.defaultLocale = newConfig.locale;
} | // Path: app/src/main/java/com/antest1/kcanotify/KcaApiData.java
// public static final int[] T3LIST_IMPROVABLE = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 19, 20, 21, 23, 24, 30, 31, 34, 36, 37, 38, 42, 43, 44, 46};
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String PREF_AKASHI_FILTERLIST = "akashi_filterlist";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String PREF_KCA_LANGUAGE = "kca_language";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static int getId(String resourceName, Class<?> c) {
// try {
// Field idField = c.getDeclaredField(resourceName);
// return idField.getInt(idField);
// } catch (Exception e) {
// throw new RuntimeException("No resource ID found for: "
// + resourceName + " / " + c, e);
// }
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static String getStringPreferences(Context ctx, String key) {
// SharedPreferences pref = ctx.getSharedPreferences("pref", Context.MODE_PRIVATE);
// try {
// return String.valueOf(pref.getInt(key, 0));
// } catch (Exception e) {
// // Nothing to do
// }
// return pref.getString(key, "");
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static String joinStr(List<String> list, String delim) {
// String resultStr = "";
// if (list.size() > 0) {
// int i;
// for (i = 0; i < list.size() - 1; i++) {
// resultStr = resultStr.concat(list.get(i));
// resultStr = resultStr.concat(delim);
// }
// resultStr = resultStr.concat(list.get(i));
// }
// return resultStr;
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static void setPreferences(Context ctx, String key, Object value) {
// SharedPreferences pref = ctx.getSharedPreferences("pref", Context.MODE_PRIVATE);
// SharedPreferences.Editor editor = pref.edit();
// if (value instanceof String) {
// editor.putString(key, (String) value);
// } else if (value instanceof Boolean) {
// editor.putBoolean(key, (Boolean) value);
// } else if (value instanceof Integer) {
// editor.putString(key, String.valueOf(value));
// } else {
// editor.putString(key, value.toString());
// }
// editor.commit();
// }
// Path: app/src/main/java/com/antest1/kcanotify/AkashiFilterActivity.java
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import androidx.core.content.ContextCompat;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import static com.antest1.kcanotify.KcaApiData.T3LIST_IMPROVABLE;
import static com.antest1.kcanotify.KcaConstants.PREF_AKASHI_FILTERLIST;
import static com.antest1.kcanotify.KcaConstants.PREF_KCA_LANGUAGE;
import static com.antest1.kcanotify.KcaUtils.getId;
import static com.antest1.kcanotify.KcaUtils.getStringPreferences;
import static com.antest1.kcanotify.KcaUtils.joinStr;
import static com.antest1.kcanotify.KcaUtils.setPreferences;
private String addFiltered(String data, int id) {
return data.concat(String.valueOf(id)).concat("|");
}
private String deleteFiltered(String data, int id) {
return data.replace(KcaUtils.format("|%d|",id), "|");
}
private void setEquipButton() {
String filter = getStringPreferences(getApplicationContext(), PREF_AKASHI_FILTERLIST);
for(int type: T3LIST_IMPROVABLE) {
int btnId = getId("akashi_filter_equip_btn_".concat(String.valueOf(type)), R.id.class);
ImageView btnView = (ImageView) findViewById(btnId);
if(checkFiltered(filter, type)) {
btnView.setBackground(ContextCompat.getDrawable(this, R.drawable.imagebtn_off));
} else {
btnView.setBackground(ContextCompat.getDrawable(this, R.drawable.imagebtn_on));
}
}
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Log.e("KCA", "lang: " + newConfig.getLocales().get(0).getLanguage() + " " + newConfig.getLocales().get(0).getCountry());
KcaApplication.defaultLocale = newConfig.getLocales().get(0);
} else {
Log.e("KCA", "lang: " + newConfig.locale.getLanguage() + " " + newConfig.locale.getCountry());
KcaApplication.defaultLocale = newConfig.locale;
} | if(getStringPreferences(getApplicationContext(), PREF_KCA_LANGUAGE).startsWith("default")) { |
antest1/kcanotify | app/src/main/java/com/antest1/kcanotify/KcaResourceLogPageAdapter.java | // Path: app/src/main/java/com/antest1/kcanotify/KcaResourcelogItemAdpater.java
// public static List<JsonObject> resourceData = new ArrayList<>();
| import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;
import android.util.Log;
import static com.antest1.kcanotify.KcaResourcelogItemAdpater.resourceData; | package com.antest1.kcanotify;
public class KcaResourceLogPageAdapter extends FragmentStatePagerAdapter {
private final static int tabCount = 2;
public KcaResourceLogPageAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
Log.e("KCA", "getItem "+position);
| // Path: app/src/main/java/com/antest1/kcanotify/KcaResourcelogItemAdpater.java
// public static List<JsonObject> resourceData = new ArrayList<>();
// Path: app/src/main/java/com/antest1/kcanotify/KcaResourceLogPageAdapter.java
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;
import android.util.Log;
import static com.antest1.kcanotify.KcaResourcelogItemAdpater.resourceData;
package com.antest1.kcanotify;
public class KcaResourceLogPageAdapter extends FragmentStatePagerAdapter {
private final static int tabCount = 2;
public KcaResourceLogPageAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
Log.e("KCA", "getItem "+position);
| KcaResoureLogFragment f = KcaResoureLogFragment.create(resourceData, position); |
antest1/kcanotify | app/src/main/java/com/antest1/kcanotify/KcaResoureLogFragment.java | // Path: app/src/main/java/com/antest1/kcanotify/KcaResourcelogItemAdpater.java
// public static List<JsonObject> resourceData = new ArrayList<>();
| import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.core.content.ContextCompat;
import androidx.appcompat.widget.AppCompatCheckBox;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.TextView;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.XAxis;
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 com.github.mikephil.charting.utils.EntryXComparator;
import com.google.gson.JsonObject;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import static android.view.View.GONE;
import static com.antest1.kcanotify.KcaResourcelogItemAdpater.resourceData; | package com.antest1.kcanotify;
public class KcaResoureLogFragment extends Fragment {
public static final long DAY_MILLISECOND = 86400000;
public int position;
final int[][] color_data = {
{ R.color.colorResourceFuel, R.color.colorResourceAmmo, R.color.colorResourceSteel, R.color.colorResourceBauxite},
{ R.color.colorConsumableBucket, R.color.colorConsumableTorch, R.color.colorConsumableDevmat, R.color.colorConsumableScrew}};
final String[][] data_key = {
{ "res_fuel", "res_ammo", "res_steel", "res_bauxite" },
{ "con_bucket", "con_torch", "con_devmat", "con_screw"}};
final static int[] maximum = {300000, 3000};
boolean[] is_draw_enabled = { true, true, true, true };
static int[] interval = {5000, 100};
static long xaxis_interval = DAY_MILLISECOND;
static String xaxis_format = "MM/dd";
KcaResourcelogItemAdpater adapter = new KcaResourcelogItemAdpater();
private String getStringWithLocale(int id) {
return KcaUtils.getStringWithLocale(getContext(), getActivity(), id);
}
public static KcaResoureLogFragment create(List<JsonObject> data, int pos) {
Log.e("KCA", "create " + pos); | // Path: app/src/main/java/com/antest1/kcanotify/KcaResourcelogItemAdpater.java
// public static List<JsonObject> resourceData = new ArrayList<>();
// Path: app/src/main/java/com/antest1/kcanotify/KcaResoureLogFragment.java
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.core.content.ContextCompat;
import androidx.appcompat.widget.AppCompatCheckBox;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.TextView;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.XAxis;
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 com.github.mikephil.charting.utils.EntryXComparator;
import com.google.gson.JsonObject;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import static android.view.View.GONE;
import static com.antest1.kcanotify.KcaResourcelogItemAdpater.resourceData;
package com.antest1.kcanotify;
public class KcaResoureLogFragment extends Fragment {
public static final long DAY_MILLISECOND = 86400000;
public int position;
final int[][] color_data = {
{ R.color.colorResourceFuel, R.color.colorResourceAmmo, R.color.colorResourceSteel, R.color.colorResourceBauxite},
{ R.color.colorConsumableBucket, R.color.colorConsumableTorch, R.color.colorConsumableDevmat, R.color.colorConsumableScrew}};
final String[][] data_key = {
{ "res_fuel", "res_ammo", "res_steel", "res_bauxite" },
{ "con_bucket", "con_torch", "con_devmat", "con_screw"}};
final static int[] maximum = {300000, 3000};
boolean[] is_draw_enabled = { true, true, true, true };
static int[] interval = {5000, 100};
static long xaxis_interval = DAY_MILLISECOND;
static String xaxis_format = "MM/dd";
KcaResourcelogItemAdpater adapter = new KcaResourcelogItemAdpater();
private String getStringWithLocale(int id) {
return KcaUtils.getStringWithLocale(getContext(), getActivity(), id);
}
public static KcaResoureLogFragment create(List<JsonObject> data, int pos) {
Log.e("KCA", "create " + pos); | resourceData = data; |
antest1/kcanotify | app/src/main/java/com/antest1/kcanotify/PackageFilterActivity.java | // Path: app/src/main/java/com/antest1/kcanotify/KcaApiData.java
// public static void loadTranslationData(Context context) {
// loadTranslationData(context, false);
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String PREF_KCA_LANGUAGE = "kca_language";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String PREF_PACKAGE_ALLOW = "package_allow";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static String getStringPreferences(Context ctx, String key) {
// SharedPreferences pref = ctx.getSharedPreferences("pref", Context.MODE_PRIVATE);
// try {
// return String.valueOf(pref.getInt(key, 0));
// } catch (Exception e) {
// // Nothing to do
// }
// return pref.getString(key, "");
// }
| import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.core.content.ContextCompat;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.TextView;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonParser;
import java.lang.ref.WeakReference;
import java.util.Locale;
import static com.antest1.kcanotify.KcaApiData.loadTranslationData;
import static com.antest1.kcanotify.KcaConstants.PREF_KCA_LANGUAGE;
import static com.antest1.kcanotify.KcaConstants.PREF_PACKAGE_ALLOW;
import static com.antest1.kcanotify.KcaUtils.getStringPreferences; | countview = findViewById(R.id.package_count);
setAllowCount();
}
@Override
protected void onDestroy() {
super.onDestroy();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Log.e("KCA", "lang: " + newConfig.getLocales().get(0).getLanguage() + " " + newConfig.getLocales().get(0).getCountry());
KcaApplication.defaultLocale = newConfig.getLocales().get(0);
} else {
Log.e("KCA", "lang: " + newConfig.locale.getLanguage() + " " + newConfig.locale.getCountry());
KcaApplication.defaultLocale = newConfig.locale;
} | // Path: app/src/main/java/com/antest1/kcanotify/KcaApiData.java
// public static void loadTranslationData(Context context) {
// loadTranslationData(context, false);
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String PREF_KCA_LANGUAGE = "kca_language";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String PREF_PACKAGE_ALLOW = "package_allow";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static String getStringPreferences(Context ctx, String key) {
// SharedPreferences pref = ctx.getSharedPreferences("pref", Context.MODE_PRIVATE);
// try {
// return String.valueOf(pref.getInt(key, 0));
// } catch (Exception e) {
// // Nothing to do
// }
// return pref.getString(key, "");
// }
// Path: app/src/main/java/com/antest1/kcanotify/PackageFilterActivity.java
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.core.content.ContextCompat;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.TextView;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonParser;
import java.lang.ref.WeakReference;
import java.util.Locale;
import static com.antest1.kcanotify.KcaApiData.loadTranslationData;
import static com.antest1.kcanotify.KcaConstants.PREF_KCA_LANGUAGE;
import static com.antest1.kcanotify.KcaConstants.PREF_PACKAGE_ALLOW;
import static com.antest1.kcanotify.KcaUtils.getStringPreferences;
countview = findViewById(R.id.package_count);
setAllowCount();
}
@Override
protected void onDestroy() {
super.onDestroy();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Log.e("KCA", "lang: " + newConfig.getLocales().get(0).getLanguage() + " " + newConfig.getLocales().get(0).getCountry());
KcaApplication.defaultLocale = newConfig.getLocales().get(0);
} else {
Log.e("KCA", "lang: " + newConfig.locale.getLanguage() + " " + newConfig.locale.getCountry());
KcaApplication.defaultLocale = newConfig.locale;
} | if(getStringPreferences(getApplicationContext(), PREF_KCA_LANGUAGE).startsWith("default")) { |
antest1/kcanotify | app/src/main/java/com/antest1/kcanotify/PackageFilterActivity.java | // Path: app/src/main/java/com/antest1/kcanotify/KcaApiData.java
// public static void loadTranslationData(Context context) {
// loadTranslationData(context, false);
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String PREF_KCA_LANGUAGE = "kca_language";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String PREF_PACKAGE_ALLOW = "package_allow";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static String getStringPreferences(Context ctx, String key) {
// SharedPreferences pref = ctx.getSharedPreferences("pref", Context.MODE_PRIVATE);
// try {
// return String.valueOf(pref.getInt(key, 0));
// } catch (Exception e) {
// // Nothing to do
// }
// return pref.getString(key, "");
// }
| import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.core.content.ContextCompat;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.TextView;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonParser;
import java.lang.ref.WeakReference;
import java.util.Locale;
import static com.antest1.kcanotify.KcaApiData.loadTranslationData;
import static com.antest1.kcanotify.KcaConstants.PREF_KCA_LANGUAGE;
import static com.antest1.kcanotify.KcaConstants.PREF_PACKAGE_ALLOW;
import static com.antest1.kcanotify.KcaUtils.getStringPreferences; | countview = findViewById(R.id.package_count);
setAllowCount();
}
@Override
protected void onDestroy() {
super.onDestroy();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Log.e("KCA", "lang: " + newConfig.getLocales().get(0).getLanguage() + " " + newConfig.getLocales().get(0).getCountry());
KcaApplication.defaultLocale = newConfig.getLocales().get(0);
} else {
Log.e("KCA", "lang: " + newConfig.locale.getLanguage() + " " + newConfig.locale.getCountry());
KcaApplication.defaultLocale = newConfig.locale;
} | // Path: app/src/main/java/com/antest1/kcanotify/KcaApiData.java
// public static void loadTranslationData(Context context) {
// loadTranslationData(context, false);
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String PREF_KCA_LANGUAGE = "kca_language";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String PREF_PACKAGE_ALLOW = "package_allow";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static String getStringPreferences(Context ctx, String key) {
// SharedPreferences pref = ctx.getSharedPreferences("pref", Context.MODE_PRIVATE);
// try {
// return String.valueOf(pref.getInt(key, 0));
// } catch (Exception e) {
// // Nothing to do
// }
// return pref.getString(key, "");
// }
// Path: app/src/main/java/com/antest1/kcanotify/PackageFilterActivity.java
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.core.content.ContextCompat;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.TextView;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonParser;
import java.lang.ref.WeakReference;
import java.util.Locale;
import static com.antest1.kcanotify.KcaApiData.loadTranslationData;
import static com.antest1.kcanotify.KcaConstants.PREF_KCA_LANGUAGE;
import static com.antest1.kcanotify.KcaConstants.PREF_PACKAGE_ALLOW;
import static com.antest1.kcanotify.KcaUtils.getStringPreferences;
countview = findViewById(R.id.package_count);
setAllowCount();
}
@Override
protected void onDestroy() {
super.onDestroy();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Log.e("KCA", "lang: " + newConfig.getLocales().get(0).getLanguage() + " " + newConfig.getLocales().get(0).getCountry());
KcaApplication.defaultLocale = newConfig.getLocales().get(0);
} else {
Log.e("KCA", "lang: " + newConfig.locale.getLanguage() + " " + newConfig.locale.getCountry());
KcaApplication.defaultLocale = newConfig.locale;
} | if(getStringPreferences(getApplicationContext(), PREF_KCA_LANGUAGE).startsWith("default")) { |
antest1/kcanotify | app/src/main/java/com/antest1/kcanotify/PackageFilterActivity.java | // Path: app/src/main/java/com/antest1/kcanotify/KcaApiData.java
// public static void loadTranslationData(Context context) {
// loadTranslationData(context, false);
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String PREF_KCA_LANGUAGE = "kca_language";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String PREF_PACKAGE_ALLOW = "package_allow";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static String getStringPreferences(Context ctx, String key) {
// SharedPreferences pref = ctx.getSharedPreferences("pref", Context.MODE_PRIVATE);
// try {
// return String.valueOf(pref.getInt(key, 0));
// } catch (Exception e) {
// // Nothing to do
// }
// return pref.getString(key, "");
// }
| import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.core.content.ContextCompat;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.TextView;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonParser;
import java.lang.ref.WeakReference;
import java.util.Locale;
import static com.antest1.kcanotify.KcaApiData.loadTranslationData;
import static com.antest1.kcanotify.KcaConstants.PREF_KCA_LANGUAGE;
import static com.antest1.kcanotify.KcaConstants.PREF_PACKAGE_ALLOW;
import static com.antest1.kcanotify.KcaUtils.getStringPreferences; | protected void onDestroy() {
super.onDestroy();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Log.e("KCA", "lang: " + newConfig.getLocales().get(0).getLanguage() + " " + newConfig.getLocales().get(0).getCountry());
KcaApplication.defaultLocale = newConfig.getLocales().get(0);
} else {
Log.e("KCA", "lang: " + newConfig.locale.getLanguage() + " " + newConfig.locale.getCountry());
KcaApplication.defaultLocale = newConfig.locale;
}
if(getStringPreferences(getApplicationContext(), PREF_KCA_LANGUAGE).startsWith("default")) {
LocaleUtils.setLocale(Locale.getDefault());
} else {
String[] pref = getStringPreferences(getApplicationContext(), PREF_KCA_LANGUAGE).split("-");
LocaleUtils.setLocale(new Locale(pref[0], pref[1]));
} | // Path: app/src/main/java/com/antest1/kcanotify/KcaApiData.java
// public static void loadTranslationData(Context context) {
// loadTranslationData(context, false);
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String PREF_KCA_LANGUAGE = "kca_language";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String PREF_PACKAGE_ALLOW = "package_allow";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static String getStringPreferences(Context ctx, String key) {
// SharedPreferences pref = ctx.getSharedPreferences("pref", Context.MODE_PRIVATE);
// try {
// return String.valueOf(pref.getInt(key, 0));
// } catch (Exception e) {
// // Nothing to do
// }
// return pref.getString(key, "");
// }
// Path: app/src/main/java/com/antest1/kcanotify/PackageFilterActivity.java
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.core.content.ContextCompat;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.TextView;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonParser;
import java.lang.ref.WeakReference;
import java.util.Locale;
import static com.antest1.kcanotify.KcaApiData.loadTranslationData;
import static com.antest1.kcanotify.KcaConstants.PREF_KCA_LANGUAGE;
import static com.antest1.kcanotify.KcaConstants.PREF_PACKAGE_ALLOW;
import static com.antest1.kcanotify.KcaUtils.getStringPreferences;
protected void onDestroy() {
super.onDestroy();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Log.e("KCA", "lang: " + newConfig.getLocales().get(0).getLanguage() + " " + newConfig.getLocales().get(0).getCountry());
KcaApplication.defaultLocale = newConfig.getLocales().get(0);
} else {
Log.e("KCA", "lang: " + newConfig.locale.getLanguage() + " " + newConfig.locale.getCountry());
KcaApplication.defaultLocale = newConfig.locale;
}
if(getStringPreferences(getApplicationContext(), PREF_KCA_LANGUAGE).startsWith("default")) {
LocaleUtils.setLocale(Locale.getDefault());
} else {
String[] pref = getStringPreferences(getApplicationContext(), PREF_KCA_LANGUAGE).split("-");
LocaleUtils.setLocale(new Locale(pref[0], pref[1]));
} | loadTranslationData(getApplicationContext()); |
antest1/kcanotify | app/src/main/java/com/antest1/kcanotify/PackageFilterActivity.java | // Path: app/src/main/java/com/antest1/kcanotify/KcaApiData.java
// public static void loadTranslationData(Context context) {
// loadTranslationData(context, false);
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String PREF_KCA_LANGUAGE = "kca_language";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String PREF_PACKAGE_ALLOW = "package_allow";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static String getStringPreferences(Context ctx, String key) {
// SharedPreferences pref = ctx.getSharedPreferences("pref", Context.MODE_PRIVATE);
// try {
// return String.valueOf(pref.getInt(key, 0));
// } catch (Exception e) {
// // Nothing to do
// }
// return pref.getString(key, "");
// }
| import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.core.content.ContextCompat;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.TextView;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonParser;
import java.lang.ref.WeakReference;
import java.util.Locale;
import static com.antest1.kcanotify.KcaApiData.loadTranslationData;
import static com.antest1.kcanotify.KcaConstants.PREF_KCA_LANGUAGE;
import static com.antest1.kcanotify.KcaConstants.PREF_PACKAGE_ALLOW;
import static com.antest1.kcanotify.KcaUtils.getStringPreferences; | Log.e("KCA", "lang: " + newConfig.locale.getLanguage() + " " + newConfig.locale.getCountry());
KcaApplication.defaultLocale = newConfig.locale;
}
if(getStringPreferences(getApplicationContext(), PREF_KCA_LANGUAGE).startsWith("default")) {
LocaleUtils.setLocale(Locale.getDefault());
} else {
String[] pref = getStringPreferences(getApplicationContext(), PREF_KCA_LANGUAGE).split("-");
LocaleUtils.setLocale(new Locale(pref[0], pref[1]));
}
loadTranslationData(getApplicationContext());
super.onConfigurationChanged(newConfig);
}
private static class UpdateHandler extends Handler {
private final WeakReference<PackageFilterActivity> mActivity;
UpdateHandler(PackageFilterActivity activity) {
mActivity = new WeakReference<PackageFilterActivity>(activity);
}
@Override
public void handleMessage(Message msg) {
PackageFilterActivity activity = mActivity.get();
if (activity != null) {
activity.setAllowCount();
}
}
}
public void setAllowCount() { | // Path: app/src/main/java/com/antest1/kcanotify/KcaApiData.java
// public static void loadTranslationData(Context context) {
// loadTranslationData(context, false);
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String PREF_KCA_LANGUAGE = "kca_language";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String PREF_PACKAGE_ALLOW = "package_allow";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static String getStringPreferences(Context ctx, String key) {
// SharedPreferences pref = ctx.getSharedPreferences("pref", Context.MODE_PRIVATE);
// try {
// return String.valueOf(pref.getInt(key, 0));
// } catch (Exception e) {
// // Nothing to do
// }
// return pref.getString(key, "");
// }
// Path: app/src/main/java/com/antest1/kcanotify/PackageFilterActivity.java
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.core.content.ContextCompat;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.TextView;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonParser;
import java.lang.ref.WeakReference;
import java.util.Locale;
import static com.antest1.kcanotify.KcaApiData.loadTranslationData;
import static com.antest1.kcanotify.KcaConstants.PREF_KCA_LANGUAGE;
import static com.antest1.kcanotify.KcaConstants.PREF_PACKAGE_ALLOW;
import static com.antest1.kcanotify.KcaUtils.getStringPreferences;
Log.e("KCA", "lang: " + newConfig.locale.getLanguage() + " " + newConfig.locale.getCountry());
KcaApplication.defaultLocale = newConfig.locale;
}
if(getStringPreferences(getApplicationContext(), PREF_KCA_LANGUAGE).startsWith("default")) {
LocaleUtils.setLocale(Locale.getDefault());
} else {
String[] pref = getStringPreferences(getApplicationContext(), PREF_KCA_LANGUAGE).split("-");
LocaleUtils.setLocale(new Locale(pref[0], pref[1]));
}
loadTranslationData(getApplicationContext());
super.onConfigurationChanged(newConfig);
}
private static class UpdateHandler extends Handler {
private final WeakReference<PackageFilterActivity> mActivity;
UpdateHandler(PackageFilterActivity activity) {
mActivity = new WeakReference<PackageFilterActivity>(activity);
}
@Override
public void handleMessage(Message msg) {
PackageFilterActivity activity = mActivity.get();
if (activity != null) {
activity.setAllowCount();
}
}
}
public void setAllowCount() { | JsonArray data = new JsonParser().parse(getStringPreferences(getApplicationContext(), PREF_PACKAGE_ALLOW)).getAsJsonArray(); |
antest1/kcanotify | app/src/main/java/com/antest1/kcanotify/KcaFleetCheckPopupService.java | // Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String DB_KEY_DECKPORT = "key_deckport";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final int KCANOTIFY_DB_VERSION = 5;
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String PREF_KCA_SEEK_CN = "kca_seek_cn";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final int SEEK_PURE = 0;
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static Context getContextWithLocale(Context ac, Context bc) {
// Locale locale;
// String[] pref_locale = getStringPreferences(ac, PREF_KCA_LANGUAGE).split("-");
// if (pref_locale[0].toLowerCase().equals("default") || pref_locale.length < 2) {
// locale = Locale.getDefault();
// } else {
// locale = new Locale(pref_locale[0], pref_locale[1]);
// }
// Configuration configuration = new Configuration(ac.getResources().getConfiguration());
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
// configuration.setLocale(locale);
// return bc.createConfigurationContext(configuration);
// } else {
// configuration.locale = locale;
// DisplayMetrics metrics = new DisplayMetrics();
// bc.getResources().updateConfiguration(configuration, bc.getResources().getDisplayMetrics());
// return bc;
// }
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static String getStringPreferences(Context ctx, String key) {
// SharedPreferences pref = ctx.getSharedPreferences("pref", Context.MODE_PRIVATE);
// try {
// return String.valueOf(pref.getInt(key, 0));
// } catch (Exception e) {
// // Nothing to do
// }
// return pref.getString(key, "");
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static int getWindowLayoutType() {
// int windowLayoutType = -1;
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// windowLayoutType = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
// } else {
// windowLayoutType = WindowManager.LayoutParams.TYPE_PHONE;
// }
// return windowLayoutType;
// }
| import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.PixelFormat;
import android.graphics.Point;
import android.os.Build;
import android.os.IBinder;
import android.provider.Settings;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationManagerCompat;
import androidx.core.content.ContextCompat;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import java.util.Calendar;
import static com.antest1.kcanotify.KcaConstants.DB_KEY_DECKPORT;
import static com.antest1.kcanotify.KcaConstants.KCANOTIFY_DB_VERSION;
import static com.antest1.kcanotify.KcaConstants.PREF_KCA_SEEK_CN;
import static com.antest1.kcanotify.KcaConstants.SEEK_PURE;
import static com.antest1.kcanotify.KcaUtils.getContextWithLocale;
import static com.antest1.kcanotify.KcaUtils.getStringPreferences;
import static com.antest1.kcanotify.KcaUtils.getWindowLayoutType; |
public static int type;
public static boolean active = false;
public static int recent_no = 0;
public static int current_func = FCHK_FUNC_SEEKTP;
public static int deck_cnt = 1;
public static boolean isActive() {
return active;
}
public String getStringWithLocale(int id) {
return KcaUtils.getStringWithLocale(getApplicationContext(), getBaseContext(), id);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
active = true;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&& !Settings.canDrawOverlays(getApplicationContext())) {
// Can not draw overlays: pass
stopSelf();
} else { | // Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String DB_KEY_DECKPORT = "key_deckport";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final int KCANOTIFY_DB_VERSION = 5;
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String PREF_KCA_SEEK_CN = "kca_seek_cn";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final int SEEK_PURE = 0;
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static Context getContextWithLocale(Context ac, Context bc) {
// Locale locale;
// String[] pref_locale = getStringPreferences(ac, PREF_KCA_LANGUAGE).split("-");
// if (pref_locale[0].toLowerCase().equals("default") || pref_locale.length < 2) {
// locale = Locale.getDefault();
// } else {
// locale = new Locale(pref_locale[0], pref_locale[1]);
// }
// Configuration configuration = new Configuration(ac.getResources().getConfiguration());
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
// configuration.setLocale(locale);
// return bc.createConfigurationContext(configuration);
// } else {
// configuration.locale = locale;
// DisplayMetrics metrics = new DisplayMetrics();
// bc.getResources().updateConfiguration(configuration, bc.getResources().getDisplayMetrics());
// return bc;
// }
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static String getStringPreferences(Context ctx, String key) {
// SharedPreferences pref = ctx.getSharedPreferences("pref", Context.MODE_PRIVATE);
// try {
// return String.valueOf(pref.getInt(key, 0));
// } catch (Exception e) {
// // Nothing to do
// }
// return pref.getString(key, "");
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static int getWindowLayoutType() {
// int windowLayoutType = -1;
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// windowLayoutType = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
// } else {
// windowLayoutType = WindowManager.LayoutParams.TYPE_PHONE;
// }
// return windowLayoutType;
// }
// Path: app/src/main/java/com/antest1/kcanotify/KcaFleetCheckPopupService.java
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.PixelFormat;
import android.graphics.Point;
import android.os.Build;
import android.os.IBinder;
import android.provider.Settings;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationManagerCompat;
import androidx.core.content.ContextCompat;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import java.util.Calendar;
import static com.antest1.kcanotify.KcaConstants.DB_KEY_DECKPORT;
import static com.antest1.kcanotify.KcaConstants.KCANOTIFY_DB_VERSION;
import static com.antest1.kcanotify.KcaConstants.PREF_KCA_SEEK_CN;
import static com.antest1.kcanotify.KcaConstants.SEEK_PURE;
import static com.antest1.kcanotify.KcaUtils.getContextWithLocale;
import static com.antest1.kcanotify.KcaUtils.getStringPreferences;
import static com.antest1.kcanotify.KcaUtils.getWindowLayoutType;
public static int type;
public static boolean active = false;
public static int recent_no = 0;
public static int current_func = FCHK_FUNC_SEEKTP;
public static int deck_cnt = 1;
public static boolean isActive() {
return active;
}
public String getStringWithLocale(int id) {
return KcaUtils.getStringWithLocale(getApplicationContext(), getBaseContext(), id);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
active = true;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&& !Settings.canDrawOverlays(getApplicationContext())) {
// Can not draw overlays: pass
stopSelf();
} else { | dbHelper = new KcaDBHelper(getApplicationContext(), null, KCANOTIFY_DB_VERSION); |
antest1/kcanotify | app/src/main/java/com/antest1/kcanotify/KcaFleetCheckPopupService.java | // Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String DB_KEY_DECKPORT = "key_deckport";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final int KCANOTIFY_DB_VERSION = 5;
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String PREF_KCA_SEEK_CN = "kca_seek_cn";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final int SEEK_PURE = 0;
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static Context getContextWithLocale(Context ac, Context bc) {
// Locale locale;
// String[] pref_locale = getStringPreferences(ac, PREF_KCA_LANGUAGE).split("-");
// if (pref_locale[0].toLowerCase().equals("default") || pref_locale.length < 2) {
// locale = Locale.getDefault();
// } else {
// locale = new Locale(pref_locale[0], pref_locale[1]);
// }
// Configuration configuration = new Configuration(ac.getResources().getConfiguration());
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
// configuration.setLocale(locale);
// return bc.createConfigurationContext(configuration);
// } else {
// configuration.locale = locale;
// DisplayMetrics metrics = new DisplayMetrics();
// bc.getResources().updateConfiguration(configuration, bc.getResources().getDisplayMetrics());
// return bc;
// }
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static String getStringPreferences(Context ctx, String key) {
// SharedPreferences pref = ctx.getSharedPreferences("pref", Context.MODE_PRIVATE);
// try {
// return String.valueOf(pref.getInt(key, 0));
// } catch (Exception e) {
// // Nothing to do
// }
// return pref.getString(key, "");
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static int getWindowLayoutType() {
// int windowLayoutType = -1;
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// windowLayoutType = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
// } else {
// windowLayoutType = WindowManager.LayoutParams.TYPE_PHONE;
// }
// return windowLayoutType;
// }
| import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.PixelFormat;
import android.graphics.Point;
import android.os.Build;
import android.os.IBinder;
import android.provider.Settings;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationManagerCompat;
import androidx.core.content.ContextCompat;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import java.util.Calendar;
import static com.antest1.kcanotify.KcaConstants.DB_KEY_DECKPORT;
import static com.antest1.kcanotify.KcaConstants.KCANOTIFY_DB_VERSION;
import static com.antest1.kcanotify.KcaConstants.PREF_KCA_SEEK_CN;
import static com.antest1.kcanotify.KcaConstants.SEEK_PURE;
import static com.antest1.kcanotify.KcaUtils.getContextWithLocale;
import static com.antest1.kcanotify.KcaUtils.getStringPreferences;
import static com.antest1.kcanotify.KcaUtils.getWindowLayoutType; | public static int recent_no = 0;
public static int current_func = FCHK_FUNC_SEEKTP;
public static int deck_cnt = 1;
public static boolean isActive() {
return active;
}
public String getStringWithLocale(int id) {
return KcaUtils.getStringWithLocale(getApplicationContext(), getBaseContext(), id);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
active = true;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&& !Settings.canDrawOverlays(getApplicationContext())) {
// Can not draw overlays: pass
stopSelf();
} else {
dbHelper = new KcaDBHelper(getApplicationContext(), null, KCANOTIFY_DB_VERSION);
deckInfoCalc = new KcaDeckInfo(getApplicationContext(), getBaseContext());
| // Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String DB_KEY_DECKPORT = "key_deckport";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final int KCANOTIFY_DB_VERSION = 5;
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String PREF_KCA_SEEK_CN = "kca_seek_cn";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final int SEEK_PURE = 0;
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static Context getContextWithLocale(Context ac, Context bc) {
// Locale locale;
// String[] pref_locale = getStringPreferences(ac, PREF_KCA_LANGUAGE).split("-");
// if (pref_locale[0].toLowerCase().equals("default") || pref_locale.length < 2) {
// locale = Locale.getDefault();
// } else {
// locale = new Locale(pref_locale[0], pref_locale[1]);
// }
// Configuration configuration = new Configuration(ac.getResources().getConfiguration());
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
// configuration.setLocale(locale);
// return bc.createConfigurationContext(configuration);
// } else {
// configuration.locale = locale;
// DisplayMetrics metrics = new DisplayMetrics();
// bc.getResources().updateConfiguration(configuration, bc.getResources().getDisplayMetrics());
// return bc;
// }
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static String getStringPreferences(Context ctx, String key) {
// SharedPreferences pref = ctx.getSharedPreferences("pref", Context.MODE_PRIVATE);
// try {
// return String.valueOf(pref.getInt(key, 0));
// } catch (Exception e) {
// // Nothing to do
// }
// return pref.getString(key, "");
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static int getWindowLayoutType() {
// int windowLayoutType = -1;
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// windowLayoutType = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
// } else {
// windowLayoutType = WindowManager.LayoutParams.TYPE_PHONE;
// }
// return windowLayoutType;
// }
// Path: app/src/main/java/com/antest1/kcanotify/KcaFleetCheckPopupService.java
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.PixelFormat;
import android.graphics.Point;
import android.os.Build;
import android.os.IBinder;
import android.provider.Settings;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationManagerCompat;
import androidx.core.content.ContextCompat;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import java.util.Calendar;
import static com.antest1.kcanotify.KcaConstants.DB_KEY_DECKPORT;
import static com.antest1.kcanotify.KcaConstants.KCANOTIFY_DB_VERSION;
import static com.antest1.kcanotify.KcaConstants.PREF_KCA_SEEK_CN;
import static com.antest1.kcanotify.KcaConstants.SEEK_PURE;
import static com.antest1.kcanotify.KcaUtils.getContextWithLocale;
import static com.antest1.kcanotify.KcaUtils.getStringPreferences;
import static com.antest1.kcanotify.KcaUtils.getWindowLayoutType;
public static int recent_no = 0;
public static int current_func = FCHK_FUNC_SEEKTP;
public static int deck_cnt = 1;
public static boolean isActive() {
return active;
}
public String getStringWithLocale(int id) {
return KcaUtils.getStringWithLocale(getApplicationContext(), getBaseContext(), id);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
active = true;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&& !Settings.canDrawOverlays(getApplicationContext())) {
// Can not draw overlays: pass
stopSelf();
} else {
dbHelper = new KcaDBHelper(getApplicationContext(), null, KCANOTIFY_DB_VERSION);
deckInfoCalc = new KcaDeckInfo(getApplicationContext(), getBaseContext());
| contextWithLocale = getContextWithLocale(getApplicationContext(), getBaseContext()); |
antest1/kcanotify | app/src/main/java/com/antest1/kcanotify/KcaFleetCheckPopupService.java | // Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String DB_KEY_DECKPORT = "key_deckport";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final int KCANOTIFY_DB_VERSION = 5;
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String PREF_KCA_SEEK_CN = "kca_seek_cn";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final int SEEK_PURE = 0;
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static Context getContextWithLocale(Context ac, Context bc) {
// Locale locale;
// String[] pref_locale = getStringPreferences(ac, PREF_KCA_LANGUAGE).split("-");
// if (pref_locale[0].toLowerCase().equals("default") || pref_locale.length < 2) {
// locale = Locale.getDefault();
// } else {
// locale = new Locale(pref_locale[0], pref_locale[1]);
// }
// Configuration configuration = new Configuration(ac.getResources().getConfiguration());
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
// configuration.setLocale(locale);
// return bc.createConfigurationContext(configuration);
// } else {
// configuration.locale = locale;
// DisplayMetrics metrics = new DisplayMetrics();
// bc.getResources().updateConfiguration(configuration, bc.getResources().getDisplayMetrics());
// return bc;
// }
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static String getStringPreferences(Context ctx, String key) {
// SharedPreferences pref = ctx.getSharedPreferences("pref", Context.MODE_PRIVATE);
// try {
// return String.valueOf(pref.getInt(key, 0));
// } catch (Exception e) {
// // Nothing to do
// }
// return pref.getString(key, "");
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static int getWindowLayoutType() {
// int windowLayoutType = -1;
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// windowLayoutType = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
// } else {
// windowLayoutType = WindowManager.LayoutParams.TYPE_PHONE;
// }
// return windowLayoutType;
// }
| import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.PixelFormat;
import android.graphics.Point;
import android.os.Build;
import android.os.IBinder;
import android.provider.Settings;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationManagerCompat;
import androidx.core.content.ContextCompat;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import java.util.Calendar;
import static com.antest1.kcanotify.KcaConstants.DB_KEY_DECKPORT;
import static com.antest1.kcanotify.KcaConstants.KCANOTIFY_DB_VERSION;
import static com.antest1.kcanotify.KcaConstants.PREF_KCA_SEEK_CN;
import static com.antest1.kcanotify.KcaConstants.SEEK_PURE;
import static com.antest1.kcanotify.KcaUtils.getContextWithLocale;
import static com.antest1.kcanotify.KcaUtils.getStringPreferences;
import static com.antest1.kcanotify.KcaUtils.getWindowLayoutType; | stopSelf();
} else {
dbHelper = new KcaDBHelper(getApplicationContext(), null, KCANOTIFY_DB_VERSION);
deckInfoCalc = new KcaDeckInfo(getApplicationContext(), getBaseContext());
contextWithLocale = getContextWithLocale(getApplicationContext(), getBaseContext());
mInflater = LayoutInflater.from(contextWithLocale);
notificationManager = NotificationManagerCompat.from(getApplicationContext());
mView = mInflater.inflate(R.layout.view_fleet_check, null);
mView.setOnTouchListener(mViewTouchListener);
mView.findViewById(R.id.view_fchk_head).setOnTouchListener(mViewTouchListener);
((TextView) mView.findViewById(R.id.view_fchk_title)).setText(getStringWithLocale(R.string.fleetcheckview_title));
for (int fchk_id: FCHK_BTN_LIST) {
mView.findViewById(fchk_id).setOnTouchListener(mViewTouchListener);
}
for (int fleet_id: FCHK_FLEET_LIST) {
mView.findViewById(fleet_id).setOnTouchListener(mViewTouchListener);
}
mView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
popupWidth = mView.getMeasuredWidth();
popupHeight = mView.getMeasuredHeight();
fchk_info = mView.findViewById(R.id.fchk_value);
mParams = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT, | // Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String DB_KEY_DECKPORT = "key_deckport";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final int KCANOTIFY_DB_VERSION = 5;
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String PREF_KCA_SEEK_CN = "kca_seek_cn";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final int SEEK_PURE = 0;
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static Context getContextWithLocale(Context ac, Context bc) {
// Locale locale;
// String[] pref_locale = getStringPreferences(ac, PREF_KCA_LANGUAGE).split("-");
// if (pref_locale[0].toLowerCase().equals("default") || pref_locale.length < 2) {
// locale = Locale.getDefault();
// } else {
// locale = new Locale(pref_locale[0], pref_locale[1]);
// }
// Configuration configuration = new Configuration(ac.getResources().getConfiguration());
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
// configuration.setLocale(locale);
// return bc.createConfigurationContext(configuration);
// } else {
// configuration.locale = locale;
// DisplayMetrics metrics = new DisplayMetrics();
// bc.getResources().updateConfiguration(configuration, bc.getResources().getDisplayMetrics());
// return bc;
// }
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static String getStringPreferences(Context ctx, String key) {
// SharedPreferences pref = ctx.getSharedPreferences("pref", Context.MODE_PRIVATE);
// try {
// return String.valueOf(pref.getInt(key, 0));
// } catch (Exception e) {
// // Nothing to do
// }
// return pref.getString(key, "");
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static int getWindowLayoutType() {
// int windowLayoutType = -1;
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// windowLayoutType = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
// } else {
// windowLayoutType = WindowManager.LayoutParams.TYPE_PHONE;
// }
// return windowLayoutType;
// }
// Path: app/src/main/java/com/antest1/kcanotify/KcaFleetCheckPopupService.java
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.PixelFormat;
import android.graphics.Point;
import android.os.Build;
import android.os.IBinder;
import android.provider.Settings;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationManagerCompat;
import androidx.core.content.ContextCompat;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import java.util.Calendar;
import static com.antest1.kcanotify.KcaConstants.DB_KEY_DECKPORT;
import static com.antest1.kcanotify.KcaConstants.KCANOTIFY_DB_VERSION;
import static com.antest1.kcanotify.KcaConstants.PREF_KCA_SEEK_CN;
import static com.antest1.kcanotify.KcaConstants.SEEK_PURE;
import static com.antest1.kcanotify.KcaUtils.getContextWithLocale;
import static com.antest1.kcanotify.KcaUtils.getStringPreferences;
import static com.antest1.kcanotify.KcaUtils.getWindowLayoutType;
stopSelf();
} else {
dbHelper = new KcaDBHelper(getApplicationContext(), null, KCANOTIFY_DB_VERSION);
deckInfoCalc = new KcaDeckInfo(getApplicationContext(), getBaseContext());
contextWithLocale = getContextWithLocale(getApplicationContext(), getBaseContext());
mInflater = LayoutInflater.from(contextWithLocale);
notificationManager = NotificationManagerCompat.from(getApplicationContext());
mView = mInflater.inflate(R.layout.view_fleet_check, null);
mView.setOnTouchListener(mViewTouchListener);
mView.findViewById(R.id.view_fchk_head).setOnTouchListener(mViewTouchListener);
((TextView) mView.findViewById(R.id.view_fchk_title)).setText(getStringWithLocale(R.string.fleetcheckview_title));
for (int fchk_id: FCHK_BTN_LIST) {
mView.findViewById(fchk_id).setOnTouchListener(mViewTouchListener);
}
for (int fleet_id: FCHK_FLEET_LIST) {
mView.findViewById(fleet_id).setOnTouchListener(mViewTouchListener);
}
mView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
popupWidth = mView.getMeasuredWidth();
popupHeight = mView.getMeasuredHeight();
fchk_info = mView.findViewById(R.id.fchk_value);
mParams = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT, | getWindowLayoutType(), |
antest1/kcanotify | app/src/main/java/com/antest1/kcanotify/KcaFleetCheckPopupService.java | // Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String DB_KEY_DECKPORT = "key_deckport";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final int KCANOTIFY_DB_VERSION = 5;
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String PREF_KCA_SEEK_CN = "kca_seek_cn";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final int SEEK_PURE = 0;
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static Context getContextWithLocale(Context ac, Context bc) {
// Locale locale;
// String[] pref_locale = getStringPreferences(ac, PREF_KCA_LANGUAGE).split("-");
// if (pref_locale[0].toLowerCase().equals("default") || pref_locale.length < 2) {
// locale = Locale.getDefault();
// } else {
// locale = new Locale(pref_locale[0], pref_locale[1]);
// }
// Configuration configuration = new Configuration(ac.getResources().getConfiguration());
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
// configuration.setLocale(locale);
// return bc.createConfigurationContext(configuration);
// } else {
// configuration.locale = locale;
// DisplayMetrics metrics = new DisplayMetrics();
// bc.getResources().updateConfiguration(configuration, bc.getResources().getDisplayMetrics());
// return bc;
// }
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static String getStringPreferences(Context ctx, String key) {
// SharedPreferences pref = ctx.getSharedPreferences("pref", Context.MODE_PRIVATE);
// try {
// return String.valueOf(pref.getInt(key, 0));
// } catch (Exception e) {
// // Nothing to do
// }
// return pref.getString(key, "");
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static int getWindowLayoutType() {
// int windowLayoutType = -1;
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// windowLayoutType = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
// } else {
// windowLayoutType = WindowManager.LayoutParams.TYPE_PHONE;
// }
// return windowLayoutType;
// }
| import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.PixelFormat;
import android.graphics.Point;
import android.os.Build;
import android.os.IBinder;
import android.provider.Settings;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationManagerCompat;
import androidx.core.content.ContextCompat;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import java.util.Calendar;
import static com.antest1.kcanotify.KcaConstants.DB_KEY_DECKPORT;
import static com.antest1.kcanotify.KcaConstants.KCANOTIFY_DB_VERSION;
import static com.antest1.kcanotify.KcaConstants.PREF_KCA_SEEK_CN;
import static com.antest1.kcanotify.KcaConstants.SEEK_PURE;
import static com.antest1.kcanotify.KcaUtils.getContextWithLocale;
import static com.antest1.kcanotify.KcaUtils.getStringPreferences;
import static com.antest1.kcanotify.KcaUtils.getWindowLayoutType; | WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
getWindowLayoutType(),
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
mParams.gravity = Gravity.TOP | Gravity.START;
Display display = ((WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
Point size = new Point();
display.getSize(size);
screenWidth = size.x;
screenHeight = size.y;
Log.e("KCA", "w/h: " + String.valueOf(screenWidth) + " " + String.valueOf(screenHeight));
mParams.x = (screenWidth - popupWidth) / 2;
mParams.y = (screenHeight - popupHeight) / 2;
mManager = (WindowManager) getSystemService(WINDOW_SERVICE);
mManager.addView(mView, mParams);
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e("KCA-MPS", "onStartCommand");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&& !Settings.canDrawOverlays(getApplicationContext())) {
// Can not draw overlays: pass
stopSelf();
} else if (intent != null && intent.getAction() != null) {
if (intent.getAction().equals(FCHK_SHOW_ACTION)) { | // Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String DB_KEY_DECKPORT = "key_deckport";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final int KCANOTIFY_DB_VERSION = 5;
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String PREF_KCA_SEEK_CN = "kca_seek_cn";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final int SEEK_PURE = 0;
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static Context getContextWithLocale(Context ac, Context bc) {
// Locale locale;
// String[] pref_locale = getStringPreferences(ac, PREF_KCA_LANGUAGE).split("-");
// if (pref_locale[0].toLowerCase().equals("default") || pref_locale.length < 2) {
// locale = Locale.getDefault();
// } else {
// locale = new Locale(pref_locale[0], pref_locale[1]);
// }
// Configuration configuration = new Configuration(ac.getResources().getConfiguration());
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
// configuration.setLocale(locale);
// return bc.createConfigurationContext(configuration);
// } else {
// configuration.locale = locale;
// DisplayMetrics metrics = new DisplayMetrics();
// bc.getResources().updateConfiguration(configuration, bc.getResources().getDisplayMetrics());
// return bc;
// }
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static String getStringPreferences(Context ctx, String key) {
// SharedPreferences pref = ctx.getSharedPreferences("pref", Context.MODE_PRIVATE);
// try {
// return String.valueOf(pref.getInt(key, 0));
// } catch (Exception e) {
// // Nothing to do
// }
// return pref.getString(key, "");
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static int getWindowLayoutType() {
// int windowLayoutType = -1;
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// windowLayoutType = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
// } else {
// windowLayoutType = WindowManager.LayoutParams.TYPE_PHONE;
// }
// return windowLayoutType;
// }
// Path: app/src/main/java/com/antest1/kcanotify/KcaFleetCheckPopupService.java
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.PixelFormat;
import android.graphics.Point;
import android.os.Build;
import android.os.IBinder;
import android.provider.Settings;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationManagerCompat;
import androidx.core.content.ContextCompat;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import java.util.Calendar;
import static com.antest1.kcanotify.KcaConstants.DB_KEY_DECKPORT;
import static com.antest1.kcanotify.KcaConstants.KCANOTIFY_DB_VERSION;
import static com.antest1.kcanotify.KcaConstants.PREF_KCA_SEEK_CN;
import static com.antest1.kcanotify.KcaConstants.SEEK_PURE;
import static com.antest1.kcanotify.KcaUtils.getContextWithLocale;
import static com.antest1.kcanotify.KcaUtils.getStringPreferences;
import static com.antest1.kcanotify.KcaUtils.getWindowLayoutType;
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
getWindowLayoutType(),
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
mParams.gravity = Gravity.TOP | Gravity.START;
Display display = ((WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
Point size = new Point();
display.getSize(size);
screenWidth = size.x;
screenHeight = size.y;
Log.e("KCA", "w/h: " + String.valueOf(screenWidth) + " " + String.valueOf(screenHeight));
mParams.x = (screenWidth - popupWidth) / 2;
mParams.y = (screenHeight - popupHeight) / 2;
mManager = (WindowManager) getSystemService(WINDOW_SERVICE);
mManager.addView(mView, mParams);
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e("KCA-MPS", "onStartCommand");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&& !Settings.canDrawOverlays(getApplicationContext())) {
// Can not draw overlays: pass
stopSelf();
} else if (intent != null && intent.getAction() != null) {
if (intent.getAction().equals(FCHK_SHOW_ACTION)) { | portdeckdata = dbHelper.getJsonArrayValue(DB_KEY_DECKPORT); |
antest1/kcanotify | app/src/main/java/com/antest1/kcanotify/KcaFleetCheckPopupService.java | // Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String DB_KEY_DECKPORT = "key_deckport";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final int KCANOTIFY_DB_VERSION = 5;
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String PREF_KCA_SEEK_CN = "kca_seek_cn";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final int SEEK_PURE = 0;
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static Context getContextWithLocale(Context ac, Context bc) {
// Locale locale;
// String[] pref_locale = getStringPreferences(ac, PREF_KCA_LANGUAGE).split("-");
// if (pref_locale[0].toLowerCase().equals("default") || pref_locale.length < 2) {
// locale = Locale.getDefault();
// } else {
// locale = new Locale(pref_locale[0], pref_locale[1]);
// }
// Configuration configuration = new Configuration(ac.getResources().getConfiguration());
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
// configuration.setLocale(locale);
// return bc.createConfigurationContext(configuration);
// } else {
// configuration.locale = locale;
// DisplayMetrics metrics = new DisplayMetrics();
// bc.getResources().updateConfiguration(configuration, bc.getResources().getDisplayMetrics());
// return bc;
// }
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static String getStringPreferences(Context ctx, String key) {
// SharedPreferences pref = ctx.getSharedPreferences("pref", Context.MODE_PRIVATE);
// try {
// return String.valueOf(pref.getInt(key, 0));
// } catch (Exception e) {
// // Nothing to do
// }
// return pref.getString(key, "");
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static int getWindowLayoutType() {
// int windowLayoutType = -1;
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// windowLayoutType = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
// } else {
// windowLayoutType = WindowManager.LayoutParams.TYPE_PHONE;
// }
// return windowLayoutType;
// }
| import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.PixelFormat;
import android.graphics.Point;
import android.os.Build;
import android.os.IBinder;
import android.provider.Settings;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationManagerCompat;
import androidx.core.content.ContextCompat;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import java.util.Calendar;
import static com.antest1.kcanotify.KcaConstants.DB_KEY_DECKPORT;
import static com.antest1.kcanotify.KcaConstants.KCANOTIFY_DB_VERSION;
import static com.antest1.kcanotify.KcaConstants.PREF_KCA_SEEK_CN;
import static com.antest1.kcanotify.KcaConstants.SEEK_PURE;
import static com.antest1.kcanotify.KcaUtils.getContextWithLocale;
import static com.antest1.kcanotify.KcaUtils.getStringPreferences;
import static com.antest1.kcanotify.KcaUtils.getWindowLayoutType; | }
@Override
public void onDestroy() {
if (mManager != null) mManager.removeView(mView);
super.onDestroy();
}
private void stopPopup() {
active = false;
stopSelf();
}
private void setText() {
if (fchk_info != null) {
int target = recent_no;
String target_str;
if (recent_no == 4) {
target = 0;
target_str = "0,1";
} else {
target_str = String.valueOf(target);
}
if (KcaApiData.isGameDataLoaded() && KcaApiData.checkUserShipDataLoaded() && portdeckdata != null) {
int cn = getSeekCn();
String seekType = getSeekType();
switch (current_func) {
case FCHK_FUNC_SEEKTP: | // Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String DB_KEY_DECKPORT = "key_deckport";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final int KCANOTIFY_DB_VERSION = 5;
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String PREF_KCA_SEEK_CN = "kca_seek_cn";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final int SEEK_PURE = 0;
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static Context getContextWithLocale(Context ac, Context bc) {
// Locale locale;
// String[] pref_locale = getStringPreferences(ac, PREF_KCA_LANGUAGE).split("-");
// if (pref_locale[0].toLowerCase().equals("default") || pref_locale.length < 2) {
// locale = Locale.getDefault();
// } else {
// locale = new Locale(pref_locale[0], pref_locale[1]);
// }
// Configuration configuration = new Configuration(ac.getResources().getConfiguration());
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
// configuration.setLocale(locale);
// return bc.createConfigurationContext(configuration);
// } else {
// configuration.locale = locale;
// DisplayMetrics metrics = new DisplayMetrics();
// bc.getResources().updateConfiguration(configuration, bc.getResources().getDisplayMetrics());
// return bc;
// }
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static String getStringPreferences(Context ctx, String key) {
// SharedPreferences pref = ctx.getSharedPreferences("pref", Context.MODE_PRIVATE);
// try {
// return String.valueOf(pref.getInt(key, 0));
// } catch (Exception e) {
// // Nothing to do
// }
// return pref.getString(key, "");
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static int getWindowLayoutType() {
// int windowLayoutType = -1;
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// windowLayoutType = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
// } else {
// windowLayoutType = WindowManager.LayoutParams.TYPE_PHONE;
// }
// return windowLayoutType;
// }
// Path: app/src/main/java/com/antest1/kcanotify/KcaFleetCheckPopupService.java
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.PixelFormat;
import android.graphics.Point;
import android.os.Build;
import android.os.IBinder;
import android.provider.Settings;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationManagerCompat;
import androidx.core.content.ContextCompat;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import java.util.Calendar;
import static com.antest1.kcanotify.KcaConstants.DB_KEY_DECKPORT;
import static com.antest1.kcanotify.KcaConstants.KCANOTIFY_DB_VERSION;
import static com.antest1.kcanotify.KcaConstants.PREF_KCA_SEEK_CN;
import static com.antest1.kcanotify.KcaConstants.SEEK_PURE;
import static com.antest1.kcanotify.KcaUtils.getContextWithLocale;
import static com.antest1.kcanotify.KcaUtils.getStringPreferences;
import static com.antest1.kcanotify.KcaUtils.getWindowLayoutType;
}
@Override
public void onDestroy() {
if (mManager != null) mManager.removeView(mView);
super.onDestroy();
}
private void stopPopup() {
active = false;
stopSelf();
}
private void setText() {
if (fchk_info != null) {
int target = recent_no;
String target_str;
if (recent_no == 4) {
target = 0;
target_str = "0,1";
} else {
target_str = String.valueOf(target);
}
if (KcaApiData.isGameDataLoaded() && KcaApiData.checkUserShipDataLoaded() && portdeckdata != null) {
int cn = getSeekCn();
String seekType = getSeekType();
switch (current_func) {
case FCHK_FUNC_SEEKTP: | int seekValue_0 = (int) deckInfoCalc.getSeekValue(portdeckdata, target_str, SEEK_PURE, KcaBattle.getEscapeFlag()); |
antest1/kcanotify | app/src/main/java/com/antest1/kcanotify/KcaFleetCheckPopupService.java | // Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String DB_KEY_DECKPORT = "key_deckport";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final int KCANOTIFY_DB_VERSION = 5;
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String PREF_KCA_SEEK_CN = "kca_seek_cn";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final int SEEK_PURE = 0;
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static Context getContextWithLocale(Context ac, Context bc) {
// Locale locale;
// String[] pref_locale = getStringPreferences(ac, PREF_KCA_LANGUAGE).split("-");
// if (pref_locale[0].toLowerCase().equals("default") || pref_locale.length < 2) {
// locale = Locale.getDefault();
// } else {
// locale = new Locale(pref_locale[0], pref_locale[1]);
// }
// Configuration configuration = new Configuration(ac.getResources().getConfiguration());
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
// configuration.setLocale(locale);
// return bc.createConfigurationContext(configuration);
// } else {
// configuration.locale = locale;
// DisplayMetrics metrics = new DisplayMetrics();
// bc.getResources().updateConfiguration(configuration, bc.getResources().getDisplayMetrics());
// return bc;
// }
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static String getStringPreferences(Context ctx, String key) {
// SharedPreferences pref = ctx.getSharedPreferences("pref", Context.MODE_PRIVATE);
// try {
// return String.valueOf(pref.getInt(key, 0));
// } catch (Exception e) {
// // Nothing to do
// }
// return pref.getString(key, "");
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static int getWindowLayoutType() {
// int windowLayoutType = -1;
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// windowLayoutType = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
// } else {
// windowLayoutType = WindowManager.LayoutParams.TYPE_PHONE;
// }
// return windowLayoutType;
// }
| import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.PixelFormat;
import android.graphics.Point;
import android.os.Build;
import android.os.IBinder;
import android.provider.Settings;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationManagerCompat;
import androidx.core.content.ContextCompat;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import java.util.Calendar;
import static com.antest1.kcanotify.KcaConstants.DB_KEY_DECKPORT;
import static com.antest1.kcanotify.KcaConstants.KCANOTIFY_DB_VERSION;
import static com.antest1.kcanotify.KcaConstants.PREF_KCA_SEEK_CN;
import static com.antest1.kcanotify.KcaConstants.SEEK_PURE;
import static com.antest1.kcanotify.KcaUtils.getContextWithLocale;
import static com.antest1.kcanotify.KcaUtils.getStringPreferences;
import static com.antest1.kcanotify.KcaUtils.getWindowLayoutType; | double seekValue_4 = deckInfoCalc.getSeekValue(portdeckdata, target_str, 4, KcaBattle.getEscapeFlag());
int[] tp = deckInfoCalc.getTPValue(portdeckdata, target_str, KcaBattle.getEscapeFlag());
fchk_info.setText(KcaUtils.format(getStringWithLocale(R.string.fleetcheckview_content_seeklos),
seekValue_0, seekValue_1, seekValue_2, seekValue_3, seekValue_4, tp[0], tp[1]));
break;
case FCHK_FUNC_AIRBATTLE:
int[] airPowerRange = deckInfoCalc.getAirPowerRange(portdeckdata, target, KcaBattle.getEscapeFlag());
JsonObject contact = deckInfoCalc.getContactProb(portdeckdata, target_str, KcaBattle.getEscapeFlag());
double start_rate_1 = contact.getAsJsonArray("stage1").get(0).getAsDouble() * 100;
double select_rate_1 = contact.getAsJsonArray("stage2").get(0).getAsDouble() * 100;
double start_rate_2 = contact.getAsJsonArray("stage1").get(1).getAsDouble() * 100;
double select_rate_2 = contact.getAsJsonArray("stage2").get(1).getAsDouble() * 100;
fchk_info.setText(KcaUtils.format(getStringWithLocale(R.string.fleetcheckview_content_airbattle),
airPowerRange[0], airPowerRange[1], start_rate_1, select_rate_1, start_rate_2, select_rate_2));
break;
case FCHK_FUNC_FUELBULL:
fchk_info.setText("fuel_bull");
break;
default:
fchk_info.setText("");
break;
}
} else {
fchk_info.setText("data not loaded");
}
}
}
private int getSeekCn() { | // Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String DB_KEY_DECKPORT = "key_deckport";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final int KCANOTIFY_DB_VERSION = 5;
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String PREF_KCA_SEEK_CN = "kca_seek_cn";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final int SEEK_PURE = 0;
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static Context getContextWithLocale(Context ac, Context bc) {
// Locale locale;
// String[] pref_locale = getStringPreferences(ac, PREF_KCA_LANGUAGE).split("-");
// if (pref_locale[0].toLowerCase().equals("default") || pref_locale.length < 2) {
// locale = Locale.getDefault();
// } else {
// locale = new Locale(pref_locale[0], pref_locale[1]);
// }
// Configuration configuration = new Configuration(ac.getResources().getConfiguration());
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
// configuration.setLocale(locale);
// return bc.createConfigurationContext(configuration);
// } else {
// configuration.locale = locale;
// DisplayMetrics metrics = new DisplayMetrics();
// bc.getResources().updateConfiguration(configuration, bc.getResources().getDisplayMetrics());
// return bc;
// }
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static String getStringPreferences(Context ctx, String key) {
// SharedPreferences pref = ctx.getSharedPreferences("pref", Context.MODE_PRIVATE);
// try {
// return String.valueOf(pref.getInt(key, 0));
// } catch (Exception e) {
// // Nothing to do
// }
// return pref.getString(key, "");
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static int getWindowLayoutType() {
// int windowLayoutType = -1;
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// windowLayoutType = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
// } else {
// windowLayoutType = WindowManager.LayoutParams.TYPE_PHONE;
// }
// return windowLayoutType;
// }
// Path: app/src/main/java/com/antest1/kcanotify/KcaFleetCheckPopupService.java
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.PixelFormat;
import android.graphics.Point;
import android.os.Build;
import android.os.IBinder;
import android.provider.Settings;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationManagerCompat;
import androidx.core.content.ContextCompat;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import java.util.Calendar;
import static com.antest1.kcanotify.KcaConstants.DB_KEY_DECKPORT;
import static com.antest1.kcanotify.KcaConstants.KCANOTIFY_DB_VERSION;
import static com.antest1.kcanotify.KcaConstants.PREF_KCA_SEEK_CN;
import static com.antest1.kcanotify.KcaConstants.SEEK_PURE;
import static com.antest1.kcanotify.KcaUtils.getContextWithLocale;
import static com.antest1.kcanotify.KcaUtils.getStringPreferences;
import static com.antest1.kcanotify.KcaUtils.getWindowLayoutType;
double seekValue_4 = deckInfoCalc.getSeekValue(portdeckdata, target_str, 4, KcaBattle.getEscapeFlag());
int[] tp = deckInfoCalc.getTPValue(portdeckdata, target_str, KcaBattle.getEscapeFlag());
fchk_info.setText(KcaUtils.format(getStringWithLocale(R.string.fleetcheckview_content_seeklos),
seekValue_0, seekValue_1, seekValue_2, seekValue_3, seekValue_4, tp[0], tp[1]));
break;
case FCHK_FUNC_AIRBATTLE:
int[] airPowerRange = deckInfoCalc.getAirPowerRange(portdeckdata, target, KcaBattle.getEscapeFlag());
JsonObject contact = deckInfoCalc.getContactProb(portdeckdata, target_str, KcaBattle.getEscapeFlag());
double start_rate_1 = contact.getAsJsonArray("stage1").get(0).getAsDouble() * 100;
double select_rate_1 = contact.getAsJsonArray("stage2").get(0).getAsDouble() * 100;
double start_rate_2 = contact.getAsJsonArray("stage1").get(1).getAsDouble() * 100;
double select_rate_2 = contact.getAsJsonArray("stage2").get(1).getAsDouble() * 100;
fchk_info.setText(KcaUtils.format(getStringWithLocale(R.string.fleetcheckview_content_airbattle),
airPowerRange[0], airPowerRange[1], start_rate_1, select_rate_1, start_rate_2, select_rate_2));
break;
case FCHK_FUNC_FUELBULL:
fchk_info.setText("fuel_bull");
break;
default:
fchk_info.setText("");
break;
}
} else {
fchk_info.setText("data not loaded");
}
}
}
private int getSeekCn() { | return Integer.valueOf(getStringPreferences(getApplicationContext(), PREF_KCA_SEEK_CN)); |
antest1/kcanotify | app/src/main/java/com/antest1/kcanotify/KcaFleetCheckPopupService.java | // Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String DB_KEY_DECKPORT = "key_deckport";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final int KCANOTIFY_DB_VERSION = 5;
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String PREF_KCA_SEEK_CN = "kca_seek_cn";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final int SEEK_PURE = 0;
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static Context getContextWithLocale(Context ac, Context bc) {
// Locale locale;
// String[] pref_locale = getStringPreferences(ac, PREF_KCA_LANGUAGE).split("-");
// if (pref_locale[0].toLowerCase().equals("default") || pref_locale.length < 2) {
// locale = Locale.getDefault();
// } else {
// locale = new Locale(pref_locale[0], pref_locale[1]);
// }
// Configuration configuration = new Configuration(ac.getResources().getConfiguration());
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
// configuration.setLocale(locale);
// return bc.createConfigurationContext(configuration);
// } else {
// configuration.locale = locale;
// DisplayMetrics metrics = new DisplayMetrics();
// bc.getResources().updateConfiguration(configuration, bc.getResources().getDisplayMetrics());
// return bc;
// }
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static String getStringPreferences(Context ctx, String key) {
// SharedPreferences pref = ctx.getSharedPreferences("pref", Context.MODE_PRIVATE);
// try {
// return String.valueOf(pref.getInt(key, 0));
// } catch (Exception e) {
// // Nothing to do
// }
// return pref.getString(key, "");
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static int getWindowLayoutType() {
// int windowLayoutType = -1;
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// windowLayoutType = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
// } else {
// windowLayoutType = WindowManager.LayoutParams.TYPE_PHONE;
// }
// return windowLayoutType;
// }
| import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.PixelFormat;
import android.graphics.Point;
import android.os.Build;
import android.os.IBinder;
import android.provider.Settings;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationManagerCompat;
import androidx.core.content.ContextCompat;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import java.util.Calendar;
import static com.antest1.kcanotify.KcaConstants.DB_KEY_DECKPORT;
import static com.antest1.kcanotify.KcaConstants.KCANOTIFY_DB_VERSION;
import static com.antest1.kcanotify.KcaConstants.PREF_KCA_SEEK_CN;
import static com.antest1.kcanotify.KcaConstants.SEEK_PURE;
import static com.antest1.kcanotify.KcaUtils.getContextWithLocale;
import static com.antest1.kcanotify.KcaUtils.getStringPreferences;
import static com.antest1.kcanotify.KcaUtils.getWindowLayoutType; | double seekValue_4 = deckInfoCalc.getSeekValue(portdeckdata, target_str, 4, KcaBattle.getEscapeFlag());
int[] tp = deckInfoCalc.getTPValue(portdeckdata, target_str, KcaBattle.getEscapeFlag());
fchk_info.setText(KcaUtils.format(getStringWithLocale(R.string.fleetcheckview_content_seeklos),
seekValue_0, seekValue_1, seekValue_2, seekValue_3, seekValue_4, tp[0], tp[1]));
break;
case FCHK_FUNC_AIRBATTLE:
int[] airPowerRange = deckInfoCalc.getAirPowerRange(portdeckdata, target, KcaBattle.getEscapeFlag());
JsonObject contact = deckInfoCalc.getContactProb(portdeckdata, target_str, KcaBattle.getEscapeFlag());
double start_rate_1 = contact.getAsJsonArray("stage1").get(0).getAsDouble() * 100;
double select_rate_1 = contact.getAsJsonArray("stage2").get(0).getAsDouble() * 100;
double start_rate_2 = contact.getAsJsonArray("stage1").get(1).getAsDouble() * 100;
double select_rate_2 = contact.getAsJsonArray("stage2").get(1).getAsDouble() * 100;
fchk_info.setText(KcaUtils.format(getStringWithLocale(R.string.fleetcheckview_content_airbattle),
airPowerRange[0], airPowerRange[1], start_rate_1, select_rate_1, start_rate_2, select_rate_2));
break;
case FCHK_FUNC_FUELBULL:
fchk_info.setText("fuel_bull");
break;
default:
fchk_info.setText("");
break;
}
} else {
fchk_info.setText("data not loaded");
}
}
}
private int getSeekCn() { | // Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String DB_KEY_DECKPORT = "key_deckport";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final int KCANOTIFY_DB_VERSION = 5;
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final String PREF_KCA_SEEK_CN = "kca_seek_cn";
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaConstants.java
// public static final int SEEK_PURE = 0;
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static Context getContextWithLocale(Context ac, Context bc) {
// Locale locale;
// String[] pref_locale = getStringPreferences(ac, PREF_KCA_LANGUAGE).split("-");
// if (pref_locale[0].toLowerCase().equals("default") || pref_locale.length < 2) {
// locale = Locale.getDefault();
// } else {
// locale = new Locale(pref_locale[0], pref_locale[1]);
// }
// Configuration configuration = new Configuration(ac.getResources().getConfiguration());
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
// configuration.setLocale(locale);
// return bc.createConfigurationContext(configuration);
// } else {
// configuration.locale = locale;
// DisplayMetrics metrics = new DisplayMetrics();
// bc.getResources().updateConfiguration(configuration, bc.getResources().getDisplayMetrics());
// return bc;
// }
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static String getStringPreferences(Context ctx, String key) {
// SharedPreferences pref = ctx.getSharedPreferences("pref", Context.MODE_PRIVATE);
// try {
// return String.valueOf(pref.getInt(key, 0));
// } catch (Exception e) {
// // Nothing to do
// }
// return pref.getString(key, "");
// }
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaUtils.java
// public static int getWindowLayoutType() {
// int windowLayoutType = -1;
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// windowLayoutType = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
// } else {
// windowLayoutType = WindowManager.LayoutParams.TYPE_PHONE;
// }
// return windowLayoutType;
// }
// Path: app/src/main/java/com/antest1/kcanotify/KcaFleetCheckPopupService.java
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.PixelFormat;
import android.graphics.Point;
import android.os.Build;
import android.os.IBinder;
import android.provider.Settings;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationManagerCompat;
import androidx.core.content.ContextCompat;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import java.util.Calendar;
import static com.antest1.kcanotify.KcaConstants.DB_KEY_DECKPORT;
import static com.antest1.kcanotify.KcaConstants.KCANOTIFY_DB_VERSION;
import static com.antest1.kcanotify.KcaConstants.PREF_KCA_SEEK_CN;
import static com.antest1.kcanotify.KcaConstants.SEEK_PURE;
import static com.antest1.kcanotify.KcaUtils.getContextWithLocale;
import static com.antest1.kcanotify.KcaUtils.getStringPreferences;
import static com.antest1.kcanotify.KcaUtils.getWindowLayoutType;
double seekValue_4 = deckInfoCalc.getSeekValue(portdeckdata, target_str, 4, KcaBattle.getEscapeFlag());
int[] tp = deckInfoCalc.getTPValue(portdeckdata, target_str, KcaBattle.getEscapeFlag());
fchk_info.setText(KcaUtils.format(getStringWithLocale(R.string.fleetcheckview_content_seeklos),
seekValue_0, seekValue_1, seekValue_2, seekValue_3, seekValue_4, tp[0], tp[1]));
break;
case FCHK_FUNC_AIRBATTLE:
int[] airPowerRange = deckInfoCalc.getAirPowerRange(portdeckdata, target, KcaBattle.getEscapeFlag());
JsonObject contact = deckInfoCalc.getContactProb(portdeckdata, target_str, KcaBattle.getEscapeFlag());
double start_rate_1 = contact.getAsJsonArray("stage1").get(0).getAsDouble() * 100;
double select_rate_1 = contact.getAsJsonArray("stage2").get(0).getAsDouble() * 100;
double start_rate_2 = contact.getAsJsonArray("stage1").get(1).getAsDouble() * 100;
double select_rate_2 = contact.getAsJsonArray("stage2").get(1).getAsDouble() * 100;
fchk_info.setText(KcaUtils.format(getStringWithLocale(R.string.fleetcheckview_content_airbattle),
airPowerRange[0], airPowerRange[1], start_rate_1, select_rate_1, start_rate_2, select_rate_2));
break;
case FCHK_FUNC_FUELBULL:
fchk_info.setText("fuel_bull");
break;
default:
fchk_info.setText("");
break;
}
} else {
fchk_info.setText("data not loaded");
}
}
}
private int getSeekCn() { | return Integer.valueOf(getStringPreferences(getApplicationContext(), PREF_KCA_SEEK_CN)); |
antest1/kcanotify | app/src/main/java/com/antest1/kcanotify/KcaDocking.java | // Path: app/src/main/java/com/antest1/kcanotify/KcaApiData.java
// public static final int STYPE_AR = 19;
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaApiData.java
// public static final int STYPE_AS = 20;
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaApiData.java
// public static final int STYPE_BB = 9;
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaApiData.java
// public static final int STYPE_BBV = 10;
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaApiData.java
// public static final int STYPE_CA = 5;
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaApiData.java
// public static final int STYPE_CAV = 6;
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaApiData.java
// public static final int STYPE_CV = 11;
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaApiData.java
// public static final int STYPE_CVB = 18;
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaApiData.java
// public static final int STYPE_CVL = 7;
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaApiData.java
// public static final int STYPE_DE = 1;
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaApiData.java
// public static final int STYPE_FBB = 8;
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaApiData.java
// public static final int STYPE_SS = 13;
| import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import static com.antest1.kcanotify.KcaApiData.STYPE_AR;
import static com.antest1.kcanotify.KcaApiData.STYPE_AS;
import static com.antest1.kcanotify.KcaApiData.STYPE_BB;
import static com.antest1.kcanotify.KcaApiData.STYPE_BBV;
import static com.antest1.kcanotify.KcaApiData.STYPE_CA;
import static com.antest1.kcanotify.KcaApiData.STYPE_CAV;
import static com.antest1.kcanotify.KcaApiData.STYPE_CV;
import static com.antest1.kcanotify.KcaApiData.STYPE_CVB;
import static com.antest1.kcanotify.KcaApiData.STYPE_CVL;
import static com.antest1.kcanotify.KcaApiData.STYPE_DE;
import static com.antest1.kcanotify.KcaApiData.STYPE_FBB;
import static com.antest1.kcanotify.KcaApiData.STYPE_SS; | public static JsonArray getDockData() { return dockdata; }
public static void setDockData(JsonArray v) { dockdata = v; }
public static long getCompleteTime(int dock) { return complete_time_check[dock]; }
public static void setCompleteTime(int dock, long time) {
complete_time_check[dock] = time;
}
public static int getShipId(int dock) { return dock_ship_id[dock]; }
public static void setShipId(int dock, int id) { dock_ship_id[dock] = id; }
public static boolean checkShipInDock(int id) {
if (id <= 0) return false;
for (int sid : dock_ship_id) {
if (sid == id) return true;
}
return false;
}
public static int getDockingTime(int hp_loss, int level, int stype) {
if (hp_loss > 0) {
int repair_time = 0;
double multiplier = getMultiplier(stype);
if (level <= 11) {
repair_time = 30 + (int) (hp_loss * (level * 10) * multiplier);
} else {
repair_time = 30 + (int) (hp_loss * ((level * 5) + Math.floor(Math.sqrt(level - 11)) * 10 + 50) * multiplier);
}
return repair_time;
} else {
return 0;
}
}
private static double getMultiplier(int type) { | // Path: app/src/main/java/com/antest1/kcanotify/KcaApiData.java
// public static final int STYPE_AR = 19;
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaApiData.java
// public static final int STYPE_AS = 20;
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaApiData.java
// public static final int STYPE_BB = 9;
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaApiData.java
// public static final int STYPE_BBV = 10;
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaApiData.java
// public static final int STYPE_CA = 5;
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaApiData.java
// public static final int STYPE_CAV = 6;
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaApiData.java
// public static final int STYPE_CV = 11;
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaApiData.java
// public static final int STYPE_CVB = 18;
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaApiData.java
// public static final int STYPE_CVL = 7;
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaApiData.java
// public static final int STYPE_DE = 1;
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaApiData.java
// public static final int STYPE_FBB = 8;
//
// Path: app/src/main/java/com/antest1/kcanotify/KcaApiData.java
// public static final int STYPE_SS = 13;
// Path: app/src/main/java/com/antest1/kcanotify/KcaDocking.java
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import static com.antest1.kcanotify.KcaApiData.STYPE_AR;
import static com.antest1.kcanotify.KcaApiData.STYPE_AS;
import static com.antest1.kcanotify.KcaApiData.STYPE_BB;
import static com.antest1.kcanotify.KcaApiData.STYPE_BBV;
import static com.antest1.kcanotify.KcaApiData.STYPE_CA;
import static com.antest1.kcanotify.KcaApiData.STYPE_CAV;
import static com.antest1.kcanotify.KcaApiData.STYPE_CV;
import static com.antest1.kcanotify.KcaApiData.STYPE_CVB;
import static com.antest1.kcanotify.KcaApiData.STYPE_CVL;
import static com.antest1.kcanotify.KcaApiData.STYPE_DE;
import static com.antest1.kcanotify.KcaApiData.STYPE_FBB;
import static com.antest1.kcanotify.KcaApiData.STYPE_SS;
public static JsonArray getDockData() { return dockdata; }
public static void setDockData(JsonArray v) { dockdata = v; }
public static long getCompleteTime(int dock) { return complete_time_check[dock]; }
public static void setCompleteTime(int dock, long time) {
complete_time_check[dock] = time;
}
public static int getShipId(int dock) { return dock_ship_id[dock]; }
public static void setShipId(int dock, int id) { dock_ship_id[dock] = id; }
public static boolean checkShipInDock(int id) {
if (id <= 0) return false;
for (int sid : dock_ship_id) {
if (sid == id) return true;
}
return false;
}
public static int getDockingTime(int hp_loss, int level, int stype) {
if (hp_loss > 0) {
int repair_time = 0;
double multiplier = getMultiplier(stype);
if (level <= 11) {
repair_time = 30 + (int) (hp_loss * (level * 10) * multiplier);
} else {
repair_time = 30 + (int) (hp_loss * ((level * 5) + Math.floor(Math.sqrt(level - 11)) * 10 + 50) * multiplier);
}
return repair_time;
} else {
return 0;
}
}
private static double getMultiplier(int type) { | if (type == STYPE_BB || type == STYPE_BBV || type == STYPE_CV || type == STYPE_CVB || type == STYPE_AR) return 2.0; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.