java WindowInsetsFrameLayout.java

WindowInsetsFrameLayout.java
package be.digitalia.common.widgets;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Rect;
import android.os.Build;
import android.support.v4.util.ObjectsCompat;
import android.util.AttributeSet;
import android.view.View;
import android.view.WindowInsets;
import android.widget.FrameLayout;

/**
 * A FrameLayout which memorizes the window insets and propagates them to child views before they are measured.
 * You can use this layout as a fragment container in place of a standard FrameLayout to
 * propagate window insets to attached fragments.
 *
 * @author Christophe Beyls
 */
public class WindowInsetsFrameLayout extends FrameLayout {

	private Object mLastInsets;

	public WindowInsetsFrameLayout(Context context) {
		super(context);
	}

	public WindowInsetsFrameLayout(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public WindowInsetsFrameLayout(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}

	@TargetApi(Build.VERSION_CODES.KITKAT_WATCH)
	@Override
	public WindowInsets onApplyWindowInsets(WindowInsets insets) {
		if (!ObjectsCompat.equals(mLastInsets, insets)) {
			mLastInsets = insets;
			requestLayout();
		}
		return insets.consumeSystemWindowInsets();
	}

	@SuppressWarnings("deprecation")
	@Override
	protected boolean fitSystemWindows(Rect insets) {
		if (!ObjectsCompat.equals(mLastInsets, insets)) {
			if (mLastInsets == null) {
				mLastInsets = new Rect(insets);
			} else {
				((Rect) mLastInsets).set(insets);
			}
			requestLayout();
		}
		return true;
	}

	@SuppressLint("DrawAllocation")
	@SuppressWarnings("deprecation")
	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		if (mLastInsets != null) {
			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
				final WindowInsets wi = (WindowInsets) mLastInsets;
				final int childCount = getChildCount();
				for (int i = 0; i < childCount; i++) {
					final View child = getChildAt(i);
					if (child.getVisibility() != GONE) {
						child.dispatchApplyWindowInsets(wi);
					}
				}
			} else {
				super.fitSystemWindows(new Rect((Rect) mLastInsets));
			}
		}
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
	}
}

java ViewPagerAdapter

ViewPagerAdapter.java
/*
 * Copyright (C) 2012 Sebastian Kaspari
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.androidzeitgeist.adapter;

import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;

/**
 * Implementation of {@link PagerAdapter} that represents each page as a {@link View}.
 *
 * @author Sebastian Kaspari <sebastian@androidzeitgeist.com>
 */
public abstract class ViewPagerAdapter extends PagerAdapter
{
    /**
     * Get a View that displays the data at the specified position in the data set.
     *
     * @param position The position of the item within the adapter's data set of the item whose view we want.
     * @param pager    The ViewPager that this view will eventually be attached to.
     *
     * @return A View corresponding to the data at the specified position.
     */
    public abstract View getView(int position, ViewPager pager);

    /**
     * Determines whether a page View is associated with a specific key object as
     * returned by instantiateItem(ViewGroup, int).
     *
     * @param view   Page View to check for association with object
     * @param object Object to check for association with view
     *
     * @return true if view is associated with the key object object.
     */
    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    /**
     * Create the page for the given position.
     *
     * @param container The containing View in which the page will be shown.
     * @param position  The page position to be instantiated.
     *
     * @return Returns an Object representing the new page. This does not need
     *         to be a View, but can be some other container of the page.
     */
    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        ViewPager pager = (ViewPager) container;
        View view = getView(position, pager);

        pager.addView(view);

        return view;
    }

    /**
     * Remove a page for the given position.
     *
     * @param container The containing View from which the page will be removed.
     * @param position  The page position to be removed.
     * @param view      The same object that was returned by instantiateItem(View, int).
     */
    @Override
    public void destroyItem(ViewGroup container, int position, Object view) {
        ((ViewPager) container).removeView((View) view);
    }
}

java FirebasePushIdGenerator

FirebaseID
public class FirebasePushIdGenerator {

	// Modeled after base64 web-safe chars, but ordered by ASCII.
	private final static String PUSH_CHARS = "-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz";

	// Timestamp of last push, used to prevent local collisions if you push twice in one ms.
	private static long LAST_PUSH_TIME = 0L;
	
	// We generate 72-bits of randomness which get turned into 12 characters and
	// appended to the timestamp to prevent collisions with other clients. We store the last
	// characters we generated because in the event of a collision, we'll use those same
	// characters except "incremented" by one.
	private static int[] LAST_RAND_CHARS = new int[72];
	
	public static synchronized String generate() {

		long now = System.currentTimeMillis();
		boolean duplicateTime = now == LAST_PUSH_TIME;
		LAST_PUSH_TIME = now;

		char[] timeStampChars = new char[8];
		for (int i = 7; i >= 0; i--) {
			timeStampChars[i] = PUSH_CHARS.charAt((int)(now % 64));
			now = (long) Math.floor(now / 64);
		}
		
		if (now != 0) {
			throw new AssertionError("We should have converted the entire timestamp.");
		}
		
		StringBuilder id = new StringBuilder(20);
		for (char c : timeStampChars) {
			id.append(c);
		}
		
		if (!duplicateTime) {
			for (int i = 0; i < 12; i++) {
				LAST_RAND_CHARS[i] = (int) Math.floor(Double.valueOf(Math.random() * 64).intValue());
			}
		} else {
			// If the timestamp hasn't changed since last push, use the same random number,
 			//except incremented by 1.
			int i=0;
			for (i = 11; i >= 0 && LAST_RAND_CHARS[i] == 63; i--) {
				LAST_RAND_CHARS[i] = 0;
			}
			LAST_RAND_CHARS[i]++;
		}
		
		for (int i = 0; i < 12; i++) {
			id.append(PUSH_CHARS.charAt(LAST_RAND_CHARS[i]));
		}
		
		if (id.length() != 20) {
			throw new AssertionError("Length should be 20.");
		}

		return id.toString();
	}
	
}

java 资源加载器

从java资源文件夹加载资源

ResourceLoader.java
import java.io.File;
import java.io.FileNotFoundException;
import java.net.URL;

public enum ResourceLoader {

    INSTANCE;

    public static File load(String fileName) throws FileNotFoundException {

        if (fileName == null || fileName.isEmpty()){
            throw new FileNotFoundException("file is not found!");
        }

        URL resource = ResourceLoader.class.getClassLoader().getResource(fileName);
        if (resource == null) {
            throw new FileNotFoundException("file is not found!");
        } else {
            return new File(resource.getFile());
        }
    }
}

java SpringBoot读取资源下文件

resource
文件位置resource/excleTemplate/test.xlsx,并且测试了四种读取方式分别的windows开发环境下(IDE中)读取和生产环境(linux下jar包运行读取)。

第一种:开发环境(IDE中)和生产环境(linux部署成jar包)都可以读取到
ClassPathResource classPathResource = new ClassPathResource("excleTemplate/test.xlsx");
InputStream inputStream =classPathResource.getInputStream();
第二种:开发环境(IDE中)和生产环境(linux部署成jar包)都可以读取到
InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("excleTemplate/test.xlsx");
第三种:开发环境(IDE中)和生产环境(linux部署成jar包)都可以读取到
InputStream inputStream = this.getClass().getResourceAsStream("/excleTemplate/test.xlsx");
第四种:开发环境(IDE中)读取正常和生产环境(linux部署成jar包)读取失败
File file = ResourceUtils.getFile("classpath:excleTemplate/test.xlsx");
InputStream inputStream = new FileInputStream(file);


第四种失败原因:
		springboot内置tomcat,打包后是一个jar包,因此通过文件读取获取流的方式行不通,因为无法直接读取压缩包中的文件,读取只能通过流的方式读取。
前三种正常原因:
		底层代码都是通过类加载器读取文件流,类加载器可以读取jar包中的编译后的class文件,当然也是可以读取jar包中的文件流了。


java ListSearch

https://www.baeldung.com/find-list-element-java <br/> <br/>#1流API <br/>#2 Google Guava <br/>#3 Apache Commons <br/>

Stream
Customer james = customers.stream()
  .filter(customer -> "James".equals(customer.getName()))
  .findAny()
  .orElse(null);
Guava
Customer james = Iterables.tryFind(customers,
  new Predicate<Customer>() {
      public boolean apply(Customer customer) {
          return "James".equals(customer.getName());
      }
  }).orNull();
Apache commons
Customer james = IterableUtils.find(customers,
  new Predicate<Customer>() {
      public boolean evaluate(Customer customer) {
          return "James".equals(customer.getName());
      }
  });

java 使用Switch Case的onClickListener

[说明链接](https://lh3.googleusercontent.com/WHH8VANn66jBsNiAMfsSqLu0Jn6cCARWIJG0kkyNNtiapUPHZXgXq7j0ubQ4d-j2c_AZAopxDw357_9S51s1nHnCJ2TTTmpEa44-WRdj0BAex7D_MiLQFwOZXkjLEUXjkmtdFUgrQZOuLti_vgzVOn6BP8kVYULPyu8DYGOnqpm9xK5CYvo5AnFiG70bweQ7aew36K4U7nFWzjMN7R9855Tu76gq43O_zHquGZr_ogJQo9w17Eqe0pNhzUR4ArAFmyehuX9Q2vm_UupPBXOqUNJUSRdIgiKFVphOHLgEMQaHrPbna15ENQwDiT7xm-uuoqBPMPgAgS4nHRIERzTbtRGkM5oRBRMBeTa9Ndkm_yQ_mc1OvMQRxR1-bj7xEBMvVih0s3Hrp4ENcDtbr5-hLzCAo8ax0GC-2Jm-krqytq33cFYvAmgKM5Y5DjXrPEMAEqYgvTFx06FIFK4F--bay4PBapsOnF8kK4wpbKMag74zzFXTPFJZhuZy__puC9Ne9oTd62LLpZ1jz7ArzEr39FhR6lqwtOR0lgmgIgRL1z9UoiJKGehN5QPLsOAqvYBfWUyEQdCLYiLD-oQKGSGtEMedss-CDPm_xaqvap3t4CUTC-bwkJW9zg51--wANYHuAeCQRwQmtB7B26e1OWRr8oAPugfUzwXAoC5AjjNDToeyNMRYaPbKbI91=w654-h969-no)

onClick.java
public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button o1;
    private Button o2;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        o1 = findViewById(R.id.Option1);
        o2 = findViewById(R.id.Option2);

        o1.setOnClickListener(this);
        o2.setOnClickListener(this);


    }


    @Override
    public void onClick(View view)
    {
        switch (view.getId()) {

            case R.id.Option1:
                Toast.makeText(MainActivity.this, "True", Toast.LENGTH_SHORT).show();
                break;

            case R.id.Option2:
                Toast.makeText(MainActivity.this, "False", Toast.LENGTH_SHORT).show();
                break;


        }
    }

    }

java JPA注释

春天JPA ##Аннотациииспользуемые

jpa.md
## Аннотация для идентификатора
***@Id*** - определяет поле сущности, которое будет использовано в качестве такого идентификатор.    
Одно из требований фреймворка — каждая таблица должна иметь такой идентификатор.
## Аннотации для генерирования последовательности
1 ***@SequenceGenerator*** - опредeление генератора последовательности
Атрибуты:
* ***name*** - имя генератора последовательности
* ***allocationSize*** - не означает, что идентификаторы сущностей увеличатся на это значение, но это число, после которого запрос к базе данных будет выполнен снова, чтобы получить следующее значение последовательности базы данных.
* ***sequenceName*** - определяется генератор последовательности,в нашем случае он был используется общий созданный заранее

2  ***@GeneratedValue*** - определяет стратегию генерации уникального идентификатора с использованием SEQUENCE

Атрибуты:
* ***strategy*** - стратегия генерации уник ИД
* ***generator*** - используемый генератор

## Аннотация для поля
1 ***@Column*** - определяет что данное поле имеет связанное отображение в БД

2 ***@Temporal*** - применяется для преобразования из типа БД SQL в J ava и обратно. Например применяется к полям или свойствам с типом java.util.Date  для преобразования из java.sql.Timestamp
jpa.java
@Id
@SequenceGenerator(name = "dish_seq", allocationSize = 1, sequenceName = "hibernate_sequence") 
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "dish_seq")
@Column(name = "id")
@Getter private Long id;

@Column(name = "created")
@Temporal(TemporalType.TIMESTAMP)
@Getter @Setter private Date created;

java 更改文字颜色

textcolor.java
// Step 1 : Create a color in color.xml file

<color name="user_color"> #008577 </color>

// user_text is the string name in strings.xml file

user_text.setTextColor(getResources().getColor(R.color.user_color));

java 烤面包

toast.java
// In Button onClick 

Toast.makeText(getApplicationContext(),"Button was pressed",Toast.LENGTH_SHORT).show();

// Using Strings.xml reference

Toast.makeText(getApplicationContext(), R.string.abc ,Toast.LENGTH_SHORT).show();