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
lemberg/d8androidsdk
sample/src/main/java/com/ls/drupal8demo/article/ArticlePreview.java
// Path: sample/src/main/java/com/ls/drupal8demo/util/ModelUtils.java // public class ModelUtils { // public final static String trimImageURL(String imageURL) // { // if(TextUtils.isEmpty(imageURL)) // { // return null; // } // // int indexIfImageStart = imageURL.indexOf("src=\""); // if(indexIfImageStart <=0) // { // return null; // }else{ // indexIfImageStart+=5; // } // // int indexOfImageEnd = imageURL.indexOf("\"",indexIfImageStart); // String result = imageURL.substring(indexIfImageStart,indexOfImageEnd); // return result; // } // }
import com.ls.drupal8demo.util.ModelUtils;
/** * The MIT License (MIT) * Copyright (c) 2014 Lemberg Solutions Limited * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.ls.drupal8demo.article; public class ArticlePreview { private String nid; private String title; private String field_blog_date; private String field_image; private String field_blog_author; private String field_blog_category; private String body; public String getNid() { return nid; } public String getTitle() { return title; } public String getDate() { return field_blog_date; } public String getAuthor() { return field_blog_author; } public String getBody() { return body; } public String getImage() {
// Path: sample/src/main/java/com/ls/drupal8demo/util/ModelUtils.java // public class ModelUtils { // public final static String trimImageURL(String imageURL) // { // if(TextUtils.isEmpty(imageURL)) // { // return null; // } // // int indexIfImageStart = imageURL.indexOf("src=\""); // if(indexIfImageStart <=0) // { // return null; // }else{ // indexIfImageStart+=5; // } // // int indexOfImageEnd = imageURL.indexOf("\"",indexIfImageStart); // String result = imageURL.substring(indexIfImageStart,indexOfImageEnd); // return result; // } // } // Path: sample/src/main/java/com/ls/drupal8demo/article/ArticlePreview.java import com.ls.drupal8demo.util.ModelUtils; /** * The MIT License (MIT) * Copyright (c) 2014 Lemberg Solutions Limited * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.ls.drupal8demo.article; public class ArticlePreview { private String nid; private String title; private String field_blog_date; private String field_image; private String field_blog_author; private String field_blog_category; private String body; public String getNid() { return nid; } public String getTitle() { return title; } public String getDate() { return field_blog_date; } public String getAuthor() { return field_blog_author; } public String getBody() { return body; } public String getImage() {
return ModelUtils.trimImageURL(this.field_image);
lemberg/d8androidsdk
DrupalSDK/src/main/java/com/ls/http/base/handler/JSONRequestHandler.java
// Path: DrupalSDK/src/main/java/com/ls/http/base/IPostableItem.java // public interface IPostableItem { // // public String toJsonString(); // // public String toXMLString(); // // public String toPlainText(); // } // // Path: DrupalSDK/src/main/java/com/ls/http/base/RequestHandler.java // public abstract class RequestHandler // { // protected final String DEFAULT_CHARSET = "utf-8"; // // protected Object object; // // public abstract String stringBodyFromItem(); // // public abstract String getBodyContentType(String defaultCharset); // // public abstract byte[]getBody(String defaultCharset) throws UnsupportedEncodingException; // // public RequestHandler() // { // // } // // protected boolean implementsPostableInterface() // { // return object instanceof IPostableItem; // } // // protected String getCharset(@Nullable String defaultCharset) // { // String charset = null; // if(object instanceof ICharsetItem) // { // charset = ((ICharsetItem)object).getCharset(); // } // // if(charset == null) // { // charset = defaultCharset;; // } // // if(charset == null) // { // charset = DEFAULT_CHARSET; // } // return charset; // } // // public Object getObject() { // return object; // } // // public void setObject(Object object) { // this.object = object; // } // // }
import com.google.gson.Gson; import com.ls.http.base.IPostableItem; import com.ls.http.base.RequestHandler; import com.ls.http.base.SharedGson; import java.io.UnsupportedEncodingException;
/* * The MIT License (MIT) * Copyright (c) 2014 Lemberg Solutions Limited * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.ls.http.base.handler; class JSONRequestHandler extends RequestHandler { @Override public String stringBodyFromItem() { if(implementsPostableInterface()) {
// Path: DrupalSDK/src/main/java/com/ls/http/base/IPostableItem.java // public interface IPostableItem { // // public String toJsonString(); // // public String toXMLString(); // // public String toPlainText(); // } // // Path: DrupalSDK/src/main/java/com/ls/http/base/RequestHandler.java // public abstract class RequestHandler // { // protected final String DEFAULT_CHARSET = "utf-8"; // // protected Object object; // // public abstract String stringBodyFromItem(); // // public abstract String getBodyContentType(String defaultCharset); // // public abstract byte[]getBody(String defaultCharset) throws UnsupportedEncodingException; // // public RequestHandler() // { // // } // // protected boolean implementsPostableInterface() // { // return object instanceof IPostableItem; // } // // protected String getCharset(@Nullable String defaultCharset) // { // String charset = null; // if(object instanceof ICharsetItem) // { // charset = ((ICharsetItem)object).getCharset(); // } // // if(charset == null) // { // charset = defaultCharset;; // } // // if(charset == null) // { // charset = DEFAULT_CHARSET; // } // return charset; // } // // public Object getObject() { // return object; // } // // public void setObject(Object object) { // this.object = object; // } // // } // Path: DrupalSDK/src/main/java/com/ls/http/base/handler/JSONRequestHandler.java import com.google.gson.Gson; import com.ls.http.base.IPostableItem; import com.ls.http.base.RequestHandler; import com.ls.http.base.SharedGson; import java.io.UnsupportedEncodingException; /* * The MIT License (MIT) * Copyright (c) 2014 Lemberg Solutions Limited * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.ls.http.base.handler; class JSONRequestHandler extends RequestHandler { @Override public String stringBodyFromItem() { if(implementsPostableInterface()) {
IPostableItem item = (IPostableItem)this.object;
lemberg/d8androidsdk
sample/src/main/java/com/ls/drupal8demo/MainActivity.java
// Path: sample/src/main/java/com/ls/drupal8demo/adapters/CategoriesAdapter.java // public class CategoriesAdapter extends FragmentPagerAdapter { // // public CategoriesAdapter(FragmentManager fm) { // super(fm); // } // // @Override // public Fragment getItem(int arg0) { // // return CategoryFragment.newInstance(AppConstants.CATEGORY.values()[arg0].id); // } // // @Override // public int getCount() { // return AppConstants.CATEGORY.values().length; // } // // }
import android.support.v7.app.ActionBar.TabListener; import android.support.v7.app.ActionBarActivity; import com.ls.drupal8demo.adapters.CategoriesAdapter; import android.os.Bundle; import android.support.v4.app.FragmentTransaction; import android.support.v4.view.ViewPager; import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBar.Tab;
/** * The MIT License (MIT) * Copyright (c) 2014 Lemberg Solutions Limited * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.ls.drupal8demo; public class MainActivity extends ActionBarActivity implements TabListener { private ViewPager mViewPager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.ac_main); final ActionBar bar = getSupportActionBar(); bar.setTitle(R.string.app_name); bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); mViewPager = (ViewPager) findViewById(R.id.pager);
// Path: sample/src/main/java/com/ls/drupal8demo/adapters/CategoriesAdapter.java // public class CategoriesAdapter extends FragmentPagerAdapter { // // public CategoriesAdapter(FragmentManager fm) { // super(fm); // } // // @Override // public Fragment getItem(int arg0) { // // return CategoryFragment.newInstance(AppConstants.CATEGORY.values()[arg0].id); // } // // @Override // public int getCount() { // return AppConstants.CATEGORY.values().length; // } // // } // Path: sample/src/main/java/com/ls/drupal8demo/MainActivity.java import android.support.v7.app.ActionBar.TabListener; import android.support.v7.app.ActionBarActivity; import com.ls.drupal8demo.adapters.CategoriesAdapter; import android.os.Bundle; import android.support.v4.app.FragmentTransaction; import android.support.v4.view.ViewPager; import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBar.Tab; /** * The MIT License (MIT) * Copyright (c) 2014 Lemberg Solutions Limited * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.ls.drupal8demo; public class MainActivity extends ActionBarActivity implements TabListener { private ViewPager mViewPager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.ac_main); final ActionBar bar = getSupportActionBar(); bar.setTitle(R.string.app_name); bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(new CategoriesAdapter(getSupportFragmentManager()));
lemberg/d8androidsdk
DrupalSDK/src/main/java/com/ls/http/base/BaseStringResponseHandler.java
// Path: DrupalSDK/src/main/java/com/ls/http/base/ResponseData.java // public class ResponseData { // protected Object data; // protected Map<String, String> headers; // protected int statusCode; // protected VolleyError error; // protected Object parsedErrorResponse; // // // /** // * @return Instance of class, specified in response or null if no such class was specified. // */ // public Object getData() { // return data; // } // // public Map<String, String> getHeaders() { // return headers; // } // // public int getStatusCode() { // return statusCode; // } // // public VolleyError getError() { // return error; // } // // /** // * // * @return parsed error response is errorResponseSpecifier was provided and error received. // */ // public Object getParsedErrorResponse() { // return parsedErrorResponse; // } // // public void cloneTo(ResponseData target) // { // target.data = data; // target.headers = headers; // target.statusCode = statusCode; // target.error = error; // target.parsedErrorResponse = parsedErrorResponse; // } // // } // // Path: DrupalSDK/src/main/java/com/ls/http/base/ResponseHandler.java // public abstract class ResponseHandler // { // protected abstract String getAcceptValueType(); // // protected abstract Response<ResponseData> parseNetworkResponse(NetworkResponse response,Object responseClassSpecifier); // }
import java.io.UnsupportedEncodingException; import java.lang.reflect.Type; import java.util.HashMap; import com.android.volley.NetworkResponse; import com.android.volley.Response; import com.android.volley.toolbox.HttpHeaderParser; import com.ls.http.base.ResponseData; import com.ls.http.base.ResponseHandler; import android.support.annotation.NonNull; import android.text.TextUtils;
/* * The MIT License (MIT) * Copyright (c) 2014 Lemberg Solutions Limited * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.ls.http.base; public abstract class BaseStringResponseHandler extends ResponseHandler { protected abstract Object itemFromResponse(@NonNull String response, @NonNull Class<?> theClass); protected abstract Object itemFromResponse(@NonNull String response, @NonNull Type theType); protected Object itemFromResponseWithSpecifier(String response, Object theSpecifier) { Object result = null; if(response != null && theSpecifier != null) { if(theSpecifier instanceof Class<?>) { result = itemFromResponse(response, (Class<?>)theSpecifier); }else if(theSpecifier instanceof Type){ result = itemFromResponse(response, (Type)theSpecifier); }else{ throw new IllegalArgumentException("You have to specify Class<?> or Type instance"); } } return result; }
// Path: DrupalSDK/src/main/java/com/ls/http/base/ResponseData.java // public class ResponseData { // protected Object data; // protected Map<String, String> headers; // protected int statusCode; // protected VolleyError error; // protected Object parsedErrorResponse; // // // /** // * @return Instance of class, specified in response or null if no such class was specified. // */ // public Object getData() { // return data; // } // // public Map<String, String> getHeaders() { // return headers; // } // // public int getStatusCode() { // return statusCode; // } // // public VolleyError getError() { // return error; // } // // /** // * // * @return parsed error response is errorResponseSpecifier was provided and error received. // */ // public Object getParsedErrorResponse() { // return parsedErrorResponse; // } // // public void cloneTo(ResponseData target) // { // target.data = data; // target.headers = headers; // target.statusCode = statusCode; // target.error = error; // target.parsedErrorResponse = parsedErrorResponse; // } // // } // // Path: DrupalSDK/src/main/java/com/ls/http/base/ResponseHandler.java // public abstract class ResponseHandler // { // protected abstract String getAcceptValueType(); // // protected abstract Response<ResponseData> parseNetworkResponse(NetworkResponse response,Object responseClassSpecifier); // } // Path: DrupalSDK/src/main/java/com/ls/http/base/BaseStringResponseHandler.java import java.io.UnsupportedEncodingException; import java.lang.reflect.Type; import java.util.HashMap; import com.android.volley.NetworkResponse; import com.android.volley.Response; import com.android.volley.toolbox.HttpHeaderParser; import com.ls.http.base.ResponseData; import com.ls.http.base.ResponseHandler; import android.support.annotation.NonNull; import android.text.TextUtils; /* * The MIT License (MIT) * Copyright (c) 2014 Lemberg Solutions Limited * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.ls.http.base; public abstract class BaseStringResponseHandler extends ResponseHandler { protected abstract Object itemFromResponse(@NonNull String response, @NonNull Class<?> theClass); protected abstract Object itemFromResponse(@NonNull String response, @NonNull Type theType); protected Object itemFromResponseWithSpecifier(String response, Object theSpecifier) { Object result = null; if(response != null && theSpecifier != null) { if(theSpecifier instanceof Class<?>) { result = itemFromResponse(response, (Class<?>)theSpecifier); }else if(theSpecifier instanceof Type){ result = itemFromResponse(response, (Type)theSpecifier); }else{ throw new IllegalArgumentException("You have to specify Class<?> or Type instance"); } } return result; }
protected Response<ResponseData> parseNetworkResponse(NetworkResponse response,Object responseClassSpecifier)
WorldSEnder/MCAnm
src/main/java/com/github/worldsender/mcanm/common/animation/stored/parts/RawAnimatedBone.java
// Path: src/main/java/com/github/worldsender/mcanm/common/animation/parts/AnimatedTransform.java // public class AnimatedTransform { // public static class AnimatedTransformBuilder { // // private final AnimatedValueBuilder builder = new AnimatedValueBuilder(); // private AnimatedTransform value = null; // // private void checkAvailable() { // value = new AnimatedTransform(); // } // // public AnimatedTransformBuilder fromStream(DataInputStream dis) throws IOException, ModelFormatException { // checkAvailable(); // value.loc_x = builder.setDefaultValue(0.0f).fromStream(dis).buildAndReset(); // value.loc_y = builder.setDefaultValue(0.0f).fromStream(dis).buildAndReset(); // value.loc_z = builder.setDefaultValue(0.0f).fromStream(dis).buildAndReset(); // value.quat_x = builder.setDefaultValue(0.0f).fromStream(dis).buildAndReset(); // value.quat_y = builder.setDefaultValue(0.0f).fromStream(dis).buildAndReset(); // value.quat_z = builder.setDefaultValue(0.0f).fromStream(dis).buildAndReset(); // value.quat_w = builder.setDefaultValue(1.0f).fromStream(dis).buildAndReset(); // value.scale_x = builder.setDefaultValue(1.0f).fromStream(dis).buildAndReset(); // value.scale_y = builder.setDefaultValue(1.0f).fromStream(dis).buildAndReset(); // value.scale_z = builder.setDefaultValue(1.0f).fromStream(dis).buildAndReset(); // return this; // } // // public AnimatedTransform buildAndReset() { // AnimatedTransform ret = value; // return ret; // } // } // // private AnimatedValue loc_x; // private AnimatedValue loc_y; // private AnimatedValue loc_z; // private AnimatedValue quat_x; // private AnimatedValue quat_y; // private AnimatedValue quat_z; // private AnimatedValue quat_w; // private AnimatedValue scale_x; // private AnimatedValue scale_y; // private AnimatedValue scale_z; // // private ThreadLocal<Vector3f> translationBuffer = ThreadLocal.withInitial(Vector3f::new); // private ThreadLocal<Quat4f> rotationBuffer = ThreadLocal.withInitial(Quat4f::new); // private ThreadLocal<Vector3f> scaleBuffer = ThreadLocal.withInitial(Vector3f::new); // // /** // * Reads a {@link AnimatedTransform} from the {@link DataInputStream} given. // * // * @param dis // */ // private AnimatedTransform() { // loc_x = loc_y = loc_z = quat_x = quat_y = quat_z = AnimatedValue.CONSTANT_ZERO; // quat_w = scale_x = scale_y = scale_z = AnimatedValue.CONSTANT_ONE; // } // // /** // * Stores the transformation of the bone at a specific point in the animation. This method interpolates between the // * nearest two key-frames using the correct interpolation mode. // * // * @param frame // * @param transform // * @param subFrame // * @return // */ // public void storeTransformAt(float frame, BoneTransformation transform) { // Vector3f t = translationBuffer.get(); // t.set(loc_x.getValueAt(frame), loc_y.getValueAt(frame), loc_z.getValueAt(frame)); // Quat4f r = rotationBuffer.get(); // r.set(quat_x.getValueAt(frame), quat_y.getValueAt(frame), quat_z.getValueAt(frame), quat_w.getValueAt(frame)); // r.normalize(); // Vector3f s = scaleBuffer.get(); // s.set(scale_x.getValueAt(frame), scale_y.getValueAt(frame), scale_z.getValueAt(frame)); // Utils.fromRTS(r, t, s, transform.matrix); // } // }
import java.util.Objects; import com.github.worldsender.mcanm.common.animation.parts.AnimatedTransform;
package com.github.worldsender.mcanm.common.animation.stored.parts; public class RawAnimatedBone { public final String name;
// Path: src/main/java/com/github/worldsender/mcanm/common/animation/parts/AnimatedTransform.java // public class AnimatedTransform { // public static class AnimatedTransformBuilder { // // private final AnimatedValueBuilder builder = new AnimatedValueBuilder(); // private AnimatedTransform value = null; // // private void checkAvailable() { // value = new AnimatedTransform(); // } // // public AnimatedTransformBuilder fromStream(DataInputStream dis) throws IOException, ModelFormatException { // checkAvailable(); // value.loc_x = builder.setDefaultValue(0.0f).fromStream(dis).buildAndReset(); // value.loc_y = builder.setDefaultValue(0.0f).fromStream(dis).buildAndReset(); // value.loc_z = builder.setDefaultValue(0.0f).fromStream(dis).buildAndReset(); // value.quat_x = builder.setDefaultValue(0.0f).fromStream(dis).buildAndReset(); // value.quat_y = builder.setDefaultValue(0.0f).fromStream(dis).buildAndReset(); // value.quat_z = builder.setDefaultValue(0.0f).fromStream(dis).buildAndReset(); // value.quat_w = builder.setDefaultValue(1.0f).fromStream(dis).buildAndReset(); // value.scale_x = builder.setDefaultValue(1.0f).fromStream(dis).buildAndReset(); // value.scale_y = builder.setDefaultValue(1.0f).fromStream(dis).buildAndReset(); // value.scale_z = builder.setDefaultValue(1.0f).fromStream(dis).buildAndReset(); // return this; // } // // public AnimatedTransform buildAndReset() { // AnimatedTransform ret = value; // return ret; // } // } // // private AnimatedValue loc_x; // private AnimatedValue loc_y; // private AnimatedValue loc_z; // private AnimatedValue quat_x; // private AnimatedValue quat_y; // private AnimatedValue quat_z; // private AnimatedValue quat_w; // private AnimatedValue scale_x; // private AnimatedValue scale_y; // private AnimatedValue scale_z; // // private ThreadLocal<Vector3f> translationBuffer = ThreadLocal.withInitial(Vector3f::new); // private ThreadLocal<Quat4f> rotationBuffer = ThreadLocal.withInitial(Quat4f::new); // private ThreadLocal<Vector3f> scaleBuffer = ThreadLocal.withInitial(Vector3f::new); // // /** // * Reads a {@link AnimatedTransform} from the {@link DataInputStream} given. // * // * @param dis // */ // private AnimatedTransform() { // loc_x = loc_y = loc_z = quat_x = quat_y = quat_z = AnimatedValue.CONSTANT_ZERO; // quat_w = scale_x = scale_y = scale_z = AnimatedValue.CONSTANT_ONE; // } // // /** // * Stores the transformation of the bone at a specific point in the animation. This method interpolates between the // * nearest two key-frames using the correct interpolation mode. // * // * @param frame // * @param transform // * @param subFrame // * @return // */ // public void storeTransformAt(float frame, BoneTransformation transform) { // Vector3f t = translationBuffer.get(); // t.set(loc_x.getValueAt(frame), loc_y.getValueAt(frame), loc_z.getValueAt(frame)); // Quat4f r = rotationBuffer.get(); // r.set(quat_x.getValueAt(frame), quat_y.getValueAt(frame), quat_z.getValueAt(frame), quat_w.getValueAt(frame)); // r.normalize(); // Vector3f s = scaleBuffer.get(); // s.set(scale_x.getValueAt(frame), scale_y.getValueAt(frame), scale_z.getValueAt(frame)); // Utils.fromRTS(r, t, s, transform.matrix); // } // } // Path: src/main/java/com/github/worldsender/mcanm/common/animation/stored/parts/RawAnimatedBone.java import java.util.Objects; import com.github.worldsender.mcanm.common.animation.parts.AnimatedTransform; package com.github.worldsender.mcanm.common.animation.stored.parts; public class RawAnimatedBone { public final String name;
public final AnimatedTransform transform;
WorldSEnder/MCAnm
src/main/java/com/github/worldsender/mcanm/common/util/ResourceCache.java
// Path: src/main/java/com/github/worldsender/mcanm/common/resource/IResource.java // public interface IResource extends Closeable { // /** // * Gets the currently open DataInputStream. // * // * @return // */ // DataInputStream getInputStream(); // // default String getResourceName() { // return getOrigin().getResourceName(); // } // // /** // * Gets the origin of the resource. If the resource has no conventional, then // * // * @return // */ // IResourceLocation getOrigin(); // } // // Path: src/main/java/com/github/worldsender/mcanm/common/resource/IResourceLocation.java // public interface IResourceLocation { // /** // * For data that has no definite location, this is suitable (e.g. one-time streams) // */ // public static final IResourceLocation UNKNOWN_LOCATION = new IResourceLocation() { // @Override // public IResource open() throws IOException { // throw new NoSuchFileException("Unknown location"); // } // // @Override // public String getResourceName() { // return "<unknown resource>"; // } // // @Override // public boolean shouldCache() { // return false; // } // // @Override // public void registerReloadListener(Consumer<IResourceLocation> reloadListener) { // reloadListener.accept(this); // // Don't store it, this location won't change // } // }; // // /** // * Opens the resource location described by this resource location. // * // * @return an empty optional if the resource is currently (expectedly) absent // * @throws IOException // * if the resource is absent unexpectedly // */ // IResource open() throws IOException; // // /** // * Registers a listener that is being fired every time this resource changes. What "changes" means is deliberately // * left unspecified but a good example would be whenever the {@link Minecraft#getResourceManager()} changes, for // * example when a new resource pack is loaded.<br> // * <b>The initial stick is considered a change already, so this method should also fire the listener once.</b> // * // * @param reloadListener // */ // void registerReloadListener(Consumer<IResourceLocation> reloadListener); // // /** // * A descriptive name of the resource, perhaps the path // * // * @return // */ // String getResourceName(); // // /** // * Returns false if this resource should not be cached, e.g. it is a one-time stream. When a // * {@link IResourceLocation} may get cached, {@link #open()} should succeed multiple times and return the same data // * every time, until the resource is reloaded. // * // * @return // */ // boolean shouldCache(); // // @Override // boolean equals(Object obj); // // @Override // int hashCode(); // }
import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.function.Function; import com.github.worldsender.mcanm.common.resource.IResource; import com.github.worldsender.mcanm.common.resource.IResourceLocation;
package com.github.worldsender.mcanm.common.util; public class ResourceCache<D> { private Map<IResourceLocation, D> cache; public ResourceCache() { cache = new HashMap<>(); }
// Path: src/main/java/com/github/worldsender/mcanm/common/resource/IResource.java // public interface IResource extends Closeable { // /** // * Gets the currently open DataInputStream. // * // * @return // */ // DataInputStream getInputStream(); // // default String getResourceName() { // return getOrigin().getResourceName(); // } // // /** // * Gets the origin of the resource. If the resource has no conventional, then // * // * @return // */ // IResourceLocation getOrigin(); // } // // Path: src/main/java/com/github/worldsender/mcanm/common/resource/IResourceLocation.java // public interface IResourceLocation { // /** // * For data that has no definite location, this is suitable (e.g. one-time streams) // */ // public static final IResourceLocation UNKNOWN_LOCATION = new IResourceLocation() { // @Override // public IResource open() throws IOException { // throw new NoSuchFileException("Unknown location"); // } // // @Override // public String getResourceName() { // return "<unknown resource>"; // } // // @Override // public boolean shouldCache() { // return false; // } // // @Override // public void registerReloadListener(Consumer<IResourceLocation> reloadListener) { // reloadListener.accept(this); // // Don't store it, this location won't change // } // }; // // /** // * Opens the resource location described by this resource location. // * // * @return an empty optional if the resource is currently (expectedly) absent // * @throws IOException // * if the resource is absent unexpectedly // */ // IResource open() throws IOException; // // /** // * Registers a listener that is being fired every time this resource changes. What "changes" means is deliberately // * left unspecified but a good example would be whenever the {@link Minecraft#getResourceManager()} changes, for // * example when a new resource pack is loaded.<br> // * <b>The initial stick is considered a change already, so this method should also fire the listener once.</b> // * // * @param reloadListener // */ // void registerReloadListener(Consumer<IResourceLocation> reloadListener); // // /** // * A descriptive name of the resource, perhaps the path // * // * @return // */ // String getResourceName(); // // /** // * Returns false if this resource should not be cached, e.g. it is a one-time stream. When a // * {@link IResourceLocation} may get cached, {@link #open()} should succeed multiple times and return the same data // * every time, until the resource is reloaded. // * // * @return // */ // boolean shouldCache(); // // @Override // boolean equals(Object obj); // // @Override // int hashCode(); // } // Path: src/main/java/com/github/worldsender/mcanm/common/util/ResourceCache.java import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.function.Function; import com.github.worldsender.mcanm.common.resource.IResource; import com.github.worldsender.mcanm.common.resource.IResourceLocation; package com.github.worldsender.mcanm.common.util; public class ResourceCache<D> { private Map<IResourceLocation, D> cache; public ResourceCache() { cache = new HashMap<>(); }
public D getOrCompute(IResource resource, Function<IResource, D> loadFunc) {
WorldSEnder/MCAnm
src/main/java/com/github/worldsender/mcanm/common/skeleton/SkeletonMCSKL.java
// Path: src/main/java/com/github/worldsender/mcanm/common/resource/IResourceLocation.java // public interface IResourceLocation { // /** // * For data that has no definite location, this is suitable (e.g. one-time streams) // */ // public static final IResourceLocation UNKNOWN_LOCATION = new IResourceLocation() { // @Override // public IResource open() throws IOException { // throw new NoSuchFileException("Unknown location"); // } // // @Override // public String getResourceName() { // return "<unknown resource>"; // } // // @Override // public boolean shouldCache() { // return false; // } // // @Override // public void registerReloadListener(Consumer<IResourceLocation> reloadListener) { // reloadListener.accept(this); // // Don't store it, this location won't change // } // }; // // /** // * Opens the resource location described by this resource location. // * // * @return an empty optional if the resource is currently (expectedly) absent // * @throws IOException // * if the resource is absent unexpectedly // */ // IResource open() throws IOException; // // /** // * Registers a listener that is being fired every time this resource changes. What "changes" means is deliberately // * left unspecified but a good example would be whenever the {@link Minecraft#getResourceManager()} changes, for // * example when a new resource pack is loaded.<br> // * <b>The initial stick is considered a change already, so this method should also fire the listener once.</b> // * // * @param reloadListener // */ // void registerReloadListener(Consumer<IResourceLocation> reloadListener); // // /** // * A descriptive name of the resource, perhaps the path // * // * @return // */ // String getResourceName(); // // /** // * Returns false if this resource should not be cached, e.g. it is a one-time stream. When a // * {@link IResourceLocation} may get cached, {@link #open()} should succeed multiple times and return the same data // * every time, until the resource is reloaded. // * // * @return // */ // boolean shouldCache(); // // @Override // boolean equals(Object obj); // // @Override // int hashCode(); // } // // Path: src/main/java/com/github/worldsender/mcanm/common/skeleton/stored/RawData.java // public class RawData implements ISkeletonVisitable { // public static final long MAGIC_NUMBER = Utils.asciiToMagicNumber("MHFC SKL"); // // public static final RawData MISSING_DATA; // // static { // MISSING_DATA = new RawData(); // MISSING_DATA.modelUUID = new UUID(0, 0); // MISSING_DATA.artist = "<unknown>"; // MISSING_DATA.specificData = new IVersionSpecificData() { // @Override // public void visitBy(ISkeletonVisitor visitor) {} // }; // } // // private static final ResourceCache<RawData> CACHE = new ResourceCache<>(); // // private static interface VersionizedModelLoader { // IVersionSpecificData loadFrom(DataInputStream dis) throws IOException, ModelFormatException; // } // // private UUID modelUUID; // private String artist; // private IVersionSpecificData specificData; // // private RawData() {} // // @Override // public void visitBy(ISkeletonVisitor visitor) { // specificData.visitBy(visitor); // visitor.visitEnd(); // } // // public static RawData retrieveFrom(IResource resource) { // return CACHE.getOrCompute(resource, r -> { // try { // return RawData.loadFrom(r); // } catch (ModelFormatException mfe) { // MCAnm.logger().error(String.format("Error loading skeleton from %s.", r.getResourceName()), mfe); // return RawData.MISSING_DATA; // } // }); // } // // private static RawData loadFrom(IResource resource) throws ModelFormatException { // RawData data = new RawData(); // DataInputStream dis = resource.getInputStream(); // // try { // long foundMagic = dis.readLong(); // if (foundMagic != MAGIC_NUMBER) { // throw new ModelFormatException( // String.format("Wrong MAGIC_NUMBER number. Found %x, expected %x.", foundMagic, MAGIC_NUMBER)); // } // // data.modelUUID = new UUID(dis.readLong(), dis.readLong()); // data.artist = Utils.readString(dis); // int version = dis.readInt(); // data.specificData = getLoaderForVersion(version).loadFrom(dis); // } catch (EOFException eofe) { // throw new ModelFormatException( // String.format("Unexpected end of file (%s).", resource.getResourceName()), // eofe); // } catch (IOException ioe) { // throw new ModelFormatException( // String.format("Can't read from stream given (%s).", resource.getResourceName()), // ioe); // } catch (ModelFormatException mfe) { // throw new ModelFormatException( // String.format("Illegal Skeleton format in %s", resource.getResourceName()), // mfe); // } // return data; // } // // private static VersionizedModelLoader getLoaderForVersion(int version) { // switch (version) { // case 1: // return RawDataV1::loadFrom; // default: // break; // } // return o -> { // throw new ModelFormatException("Unknown version: " + version); // }; // } // // @Override // public String toString() { // return "Skeleton[artist=" + artist + ", modelUUID=" + modelUUID + "]"; // } // // }
import com.github.worldsender.mcanm.common.resource.IResourceLocation; import com.github.worldsender.mcanm.common.skeleton.stored.RawData;
package com.github.worldsender.mcanm.common.skeleton; public class SkeletonMCSKL extends AbstractSkeleton { public SkeletonMCSKL(IResourceLocation resLoc) {
// Path: src/main/java/com/github/worldsender/mcanm/common/resource/IResourceLocation.java // public interface IResourceLocation { // /** // * For data that has no definite location, this is suitable (e.g. one-time streams) // */ // public static final IResourceLocation UNKNOWN_LOCATION = new IResourceLocation() { // @Override // public IResource open() throws IOException { // throw new NoSuchFileException("Unknown location"); // } // // @Override // public String getResourceName() { // return "<unknown resource>"; // } // // @Override // public boolean shouldCache() { // return false; // } // // @Override // public void registerReloadListener(Consumer<IResourceLocation> reloadListener) { // reloadListener.accept(this); // // Don't store it, this location won't change // } // }; // // /** // * Opens the resource location described by this resource location. // * // * @return an empty optional if the resource is currently (expectedly) absent // * @throws IOException // * if the resource is absent unexpectedly // */ // IResource open() throws IOException; // // /** // * Registers a listener that is being fired every time this resource changes. What "changes" means is deliberately // * left unspecified but a good example would be whenever the {@link Minecraft#getResourceManager()} changes, for // * example when a new resource pack is loaded.<br> // * <b>The initial stick is considered a change already, so this method should also fire the listener once.</b> // * // * @param reloadListener // */ // void registerReloadListener(Consumer<IResourceLocation> reloadListener); // // /** // * A descriptive name of the resource, perhaps the path // * // * @return // */ // String getResourceName(); // // /** // * Returns false if this resource should not be cached, e.g. it is a one-time stream. When a // * {@link IResourceLocation} may get cached, {@link #open()} should succeed multiple times and return the same data // * every time, until the resource is reloaded. // * // * @return // */ // boolean shouldCache(); // // @Override // boolean equals(Object obj); // // @Override // int hashCode(); // } // // Path: src/main/java/com/github/worldsender/mcanm/common/skeleton/stored/RawData.java // public class RawData implements ISkeletonVisitable { // public static final long MAGIC_NUMBER = Utils.asciiToMagicNumber("MHFC SKL"); // // public static final RawData MISSING_DATA; // // static { // MISSING_DATA = new RawData(); // MISSING_DATA.modelUUID = new UUID(0, 0); // MISSING_DATA.artist = "<unknown>"; // MISSING_DATA.specificData = new IVersionSpecificData() { // @Override // public void visitBy(ISkeletonVisitor visitor) {} // }; // } // // private static final ResourceCache<RawData> CACHE = new ResourceCache<>(); // // private static interface VersionizedModelLoader { // IVersionSpecificData loadFrom(DataInputStream dis) throws IOException, ModelFormatException; // } // // private UUID modelUUID; // private String artist; // private IVersionSpecificData specificData; // // private RawData() {} // // @Override // public void visitBy(ISkeletonVisitor visitor) { // specificData.visitBy(visitor); // visitor.visitEnd(); // } // // public static RawData retrieveFrom(IResource resource) { // return CACHE.getOrCompute(resource, r -> { // try { // return RawData.loadFrom(r); // } catch (ModelFormatException mfe) { // MCAnm.logger().error(String.format("Error loading skeleton from %s.", r.getResourceName()), mfe); // return RawData.MISSING_DATA; // } // }); // } // // private static RawData loadFrom(IResource resource) throws ModelFormatException { // RawData data = new RawData(); // DataInputStream dis = resource.getInputStream(); // // try { // long foundMagic = dis.readLong(); // if (foundMagic != MAGIC_NUMBER) { // throw new ModelFormatException( // String.format("Wrong MAGIC_NUMBER number. Found %x, expected %x.", foundMagic, MAGIC_NUMBER)); // } // // data.modelUUID = new UUID(dis.readLong(), dis.readLong()); // data.artist = Utils.readString(dis); // int version = dis.readInt(); // data.specificData = getLoaderForVersion(version).loadFrom(dis); // } catch (EOFException eofe) { // throw new ModelFormatException( // String.format("Unexpected end of file (%s).", resource.getResourceName()), // eofe); // } catch (IOException ioe) { // throw new ModelFormatException( // String.format("Can't read from stream given (%s).", resource.getResourceName()), // ioe); // } catch (ModelFormatException mfe) { // throw new ModelFormatException( // String.format("Illegal Skeleton format in %s", resource.getResourceName()), // mfe); // } // return data; // } // // private static VersionizedModelLoader getLoaderForVersion(int version) { // switch (version) { // case 1: // return RawDataV1::loadFrom; // default: // break; // } // return o -> { // throw new ModelFormatException("Unknown version: " + version); // }; // } // // @Override // public String toString() { // return "Skeleton[artist=" + artist + ", modelUUID=" + modelUUID + "]"; // } // // } // Path: src/main/java/com/github/worldsender/mcanm/common/skeleton/SkeletonMCSKL.java import com.github.worldsender.mcanm.common.resource.IResourceLocation; import com.github.worldsender.mcanm.common.skeleton.stored.RawData; package com.github.worldsender.mcanm.common.skeleton; public class SkeletonMCSKL extends AbstractSkeleton { public SkeletonMCSKL(IResourceLocation resLoc) {
super(resLoc, RawData::retrieveFrom);
WorldSEnder/MCAnm
src/main/java/com/github/worldsender/mcanm/client/model/util/Animations.java
// Path: src/main/java/com/github/worldsender/mcanm/common/animation/IAnimation.java // public interface IAnimation { // /** // * Describes a BoneTransformation, including rotation, translation and scaling. This class is opaque i.e. all // * getters and setters don't make defensive copies and states can be manipulated from the outside. // * // * @author WorldSEnder // * // */ // public static class BoneTransformation { // public static final BoneTransformation identity = new BoneTransformation(); // // private static Vector3f identityScale() { // return new Vector3f(1.0F, 1.0F, 1.0F); // } // // public final Matrix4f matrix; // // public BoneTransformation() { // this(null, null, null); // } // // public BoneTransformation(Vector3f translation, Quat4f quat) { // this(translation, quat, identityScale()); // } // // public BoneTransformation(Vector3f translation, Quat4f quat, Vector3f scale) { // if (quat == null) // quat = new Quat4f(); // if (translation == null) // translation = new Vector3f(); // if (scale == null) // scale = identityScale(); // this.matrix = Utils.fromRTS(quat, translation, scale, new Matrix4f()); // } // // public Matrix4f getMatrix() { // return matrix; // } // } // // /** // * Stores the bone's current {@link BoneTransformation} in transform(identified by name). <br> // * If the requested bone is not known to the animation transform is left untouched and this return // * <code>false</code>. Otherwise transform is set to the bone's current transform state. // * // * @param bone // * the name of the bone the matrix is requested // * @param frame // * the current frame in the animation // * @param transform // * the transform to set // * @return if a transformation has been set // */ // public boolean storeCurrentTransformation(String bone, float frame, BoneTransformation transform); // } // // Path: src/main/java/com/github/worldsender/mcanm/common/animation/IAnimation.java // public static class BoneTransformation { // public static final BoneTransformation identity = new BoneTransformation(); // // private static Vector3f identityScale() { // return new Vector3f(1.0F, 1.0F, 1.0F); // } // // public final Matrix4f matrix; // // public BoneTransformation() { // this(null, null, null); // } // // public BoneTransformation(Vector3f translation, Quat4f quat) { // this(translation, quat, identityScale()); // } // // public BoneTransformation(Vector3f translation, Quat4f quat, Vector3f scale) { // if (quat == null) // quat = new Quat4f(); // if (translation == null) // translation = new Vector3f(); // if (scale == null) // scale = identityScale(); // this.matrix = Utils.fromRTS(quat, translation, scale, new Matrix4f()); // } // // public Matrix4f getMatrix() { // return matrix; // } // }
import java.util.Arrays; import com.github.worldsender.mcanm.common.animation.IAnimation; import com.github.worldsender.mcanm.common.animation.IAnimation.BoneTransformation;
package com.github.worldsender.mcanm.client.model.util; public class Animations { /** * A wrapper to chain animations together. If a position for bone &lt;bone&gt; is not given by the firstChoice, it * subsequently asks the second choice and then the other choices.<br> * The animations returned returns no {@link BoneTransformation} if and only if none of the animations would return * a Transformation. Else the Transformation of the first animation that does return one is returned. * * @param choices * the choices, in the induced order. Usually two or more are given * @return an animation that picks it's transforms from the animations given. */ public static IAnimation combined(final IAnimation... choices) { return combined(Arrays.asList(choices)); } /** * The same as {@link #combined(IAnimation...)}, but the animations are given as an {@link Iterable}. * * @param choices * the choices to choose from, in the induced order. * @return an animation that picks it's transforms from the animations given * @see #combined(IAnimation...) */ public static IAnimation combined(final Iterable<IAnimation> choices) { return new IAnimation() { @Override
// Path: src/main/java/com/github/worldsender/mcanm/common/animation/IAnimation.java // public interface IAnimation { // /** // * Describes a BoneTransformation, including rotation, translation and scaling. This class is opaque i.e. all // * getters and setters don't make defensive copies and states can be manipulated from the outside. // * // * @author WorldSEnder // * // */ // public static class BoneTransformation { // public static final BoneTransformation identity = new BoneTransformation(); // // private static Vector3f identityScale() { // return new Vector3f(1.0F, 1.0F, 1.0F); // } // // public final Matrix4f matrix; // // public BoneTransformation() { // this(null, null, null); // } // // public BoneTransformation(Vector3f translation, Quat4f quat) { // this(translation, quat, identityScale()); // } // // public BoneTransformation(Vector3f translation, Quat4f quat, Vector3f scale) { // if (quat == null) // quat = new Quat4f(); // if (translation == null) // translation = new Vector3f(); // if (scale == null) // scale = identityScale(); // this.matrix = Utils.fromRTS(quat, translation, scale, new Matrix4f()); // } // // public Matrix4f getMatrix() { // return matrix; // } // } // // /** // * Stores the bone's current {@link BoneTransformation} in transform(identified by name). <br> // * If the requested bone is not known to the animation transform is left untouched and this return // * <code>false</code>. Otherwise transform is set to the bone's current transform state. // * // * @param bone // * the name of the bone the matrix is requested // * @param frame // * the current frame in the animation // * @param transform // * the transform to set // * @return if a transformation has been set // */ // public boolean storeCurrentTransformation(String bone, float frame, BoneTransformation transform); // } // // Path: src/main/java/com/github/worldsender/mcanm/common/animation/IAnimation.java // public static class BoneTransformation { // public static final BoneTransformation identity = new BoneTransformation(); // // private static Vector3f identityScale() { // return new Vector3f(1.0F, 1.0F, 1.0F); // } // // public final Matrix4f matrix; // // public BoneTransformation() { // this(null, null, null); // } // // public BoneTransformation(Vector3f translation, Quat4f quat) { // this(translation, quat, identityScale()); // } // // public BoneTransformation(Vector3f translation, Quat4f quat, Vector3f scale) { // if (quat == null) // quat = new Quat4f(); // if (translation == null) // translation = new Vector3f(); // if (scale == null) // scale = identityScale(); // this.matrix = Utils.fromRTS(quat, translation, scale, new Matrix4f()); // } // // public Matrix4f getMatrix() { // return matrix; // } // } // Path: src/main/java/com/github/worldsender/mcanm/client/model/util/Animations.java import java.util.Arrays; import com.github.worldsender.mcanm.common.animation.IAnimation; import com.github.worldsender.mcanm.common.animation.IAnimation.BoneTransformation; package com.github.worldsender.mcanm.client.model.util; public class Animations { /** * A wrapper to chain animations together. If a position for bone &lt;bone&gt; is not given by the firstChoice, it * subsequently asks the second choice and then the other choices.<br> * The animations returned returns no {@link BoneTransformation} if and only if none of the animations would return * a Transformation. Else the Transformation of the first animation that does return one is returned. * * @param choices * the choices, in the induced order. Usually two or more are given * @return an animation that picks it's transforms from the animations given. */ public static IAnimation combined(final IAnimation... choices) { return combined(Arrays.asList(choices)); } /** * The same as {@link #combined(IAnimation...)}, but the animations are given as an {@link Iterable}. * * @param choices * the choices to choose from, in the induced order. * @return an animation that picks it's transforms from the animations given * @see #combined(IAnimation...) */ public static IAnimation combined(final Iterable<IAnimation> choices) { return new IAnimation() { @Override
public boolean storeCurrentTransformation(String bone, float frame, BoneTransformation transform) {
WorldSEnder/MCAnm
src/main/java/com/github/worldsender/mcanm/client/model/IEntityAnimator.java
// Path: src/main/java/com/github/worldsender/mcanm/client/model/util/RenderPassInformation.java // public class RenderPassInformation extends ModelStateInformation implements IRenderPassInformation { // public static final Function<String, ResourceLocation> makeCachingTransform( // Function<String, ResourceLocation> cacheLoader) { // LoadingCache<String, ResourceLocation> cachedResourceLoc = CacheBuilder.newBuilder().maximumSize(100) // .build(new CacheLoader<String, ResourceLocation>() { // @Override // public ResourceLocation load(String key) { // return cacheLoader.apply(key); // } // }); // return cachedResourceLoc::getUnchecked; // } // // public static final Function<String, ResourceLocation> TRANSFORM_DIRECT = makeCachingTransform( // ResourceLocation::new); // /** // * This is the default texture rebinding, it just returns the given resource-location and as such does not change // * the bound texture. // */ // public static final Function<ResourceLocation, ResourceLocation> IDENTITY = Function.identity(); // // private Function<String, ResourceLocation> textureRemap; // // public RenderPassInformation() { // this.reset(); // } // // public RenderPassInformation( // float frame, // Optional<IAnimation> animation, // Optional<Predicate<String>> partPredicate, // Optional<Function<String, ResourceLocation>> resourceRemap) { // this.setFrame(frame).setAnimation(animation).setPartPredicate(partPredicate).setTextureTransform(resourceRemap); // } // // /** // * Resets this information to be reused. // */ // @Override // public void reset() { // super.reset(); // this.setTextureTransform(Optional.empty()); // } // // @Override // public ResourceLocation getActualResourceLocation(String in) { // return this.textureRemap.apply(in); // } // // @Override // public RenderPassInformation setAnimation(Optional<IAnimation> animation) { // super.setAnimation(animation); // return this; // } // // @Override // public RenderPassInformation setAnimation(IAnimation animation) { // super.setAnimation(animation); // return this; // } // // /** // * @param frame // * the frame to set // */ // @Override // public RenderPassInformation setFrame(float frame) { // super.setFrame(frame); // return this; // } // // /** // * @param partPredicate // * the partPredicate to set, Optional.empty() for RENDER_ALL // */ // @Override // public RenderPassInformation setPartPredicate(Optional<Predicate<String>> partPredicate) { // super.setPartPredicate(partPredicate); // return this; // } // // @Override // public RenderPassInformation setPartPredicate(Predicate<String> partPredicate) { // super.setPartPredicate(partPredicate); // return this; // } // // public RenderPassInformation setTextureTransform(Optional<Function<String, ResourceLocation>> textureRemap) { // return setTextureTransform(textureRemap.orElse(TRANSFORM_DIRECT)); // } // // public RenderPassInformation setTextureTransform(Function<String, ResourceLocation> textureRemap) { // this.textureRemap = Objects.requireNonNull(textureRemap); // return this; // } // }
import com.github.worldsender.mcanm.client.model.util.RenderPassInformation; import net.minecraft.entity.EntityLiving;
package com.github.worldsender.mcanm.client.model; public interface IEntityAnimator<T extends EntityLiving> { public static final IEntityAnimator<EntityLiving> STATIC_ANIMATOR = new IEntityAnimator<EntityLiving>() { @Override public IRenderPassInformation preRenderCallback( EntityLiving entity,
// Path: src/main/java/com/github/worldsender/mcanm/client/model/util/RenderPassInformation.java // public class RenderPassInformation extends ModelStateInformation implements IRenderPassInformation { // public static final Function<String, ResourceLocation> makeCachingTransform( // Function<String, ResourceLocation> cacheLoader) { // LoadingCache<String, ResourceLocation> cachedResourceLoc = CacheBuilder.newBuilder().maximumSize(100) // .build(new CacheLoader<String, ResourceLocation>() { // @Override // public ResourceLocation load(String key) { // return cacheLoader.apply(key); // } // }); // return cachedResourceLoc::getUnchecked; // } // // public static final Function<String, ResourceLocation> TRANSFORM_DIRECT = makeCachingTransform( // ResourceLocation::new); // /** // * This is the default texture rebinding, it just returns the given resource-location and as such does not change // * the bound texture. // */ // public static final Function<ResourceLocation, ResourceLocation> IDENTITY = Function.identity(); // // private Function<String, ResourceLocation> textureRemap; // // public RenderPassInformation() { // this.reset(); // } // // public RenderPassInformation( // float frame, // Optional<IAnimation> animation, // Optional<Predicate<String>> partPredicate, // Optional<Function<String, ResourceLocation>> resourceRemap) { // this.setFrame(frame).setAnimation(animation).setPartPredicate(partPredicate).setTextureTransform(resourceRemap); // } // // /** // * Resets this information to be reused. // */ // @Override // public void reset() { // super.reset(); // this.setTextureTransform(Optional.empty()); // } // // @Override // public ResourceLocation getActualResourceLocation(String in) { // return this.textureRemap.apply(in); // } // // @Override // public RenderPassInformation setAnimation(Optional<IAnimation> animation) { // super.setAnimation(animation); // return this; // } // // @Override // public RenderPassInformation setAnimation(IAnimation animation) { // super.setAnimation(animation); // return this; // } // // /** // * @param frame // * the frame to set // */ // @Override // public RenderPassInformation setFrame(float frame) { // super.setFrame(frame); // return this; // } // // /** // * @param partPredicate // * the partPredicate to set, Optional.empty() for RENDER_ALL // */ // @Override // public RenderPassInformation setPartPredicate(Optional<Predicate<String>> partPredicate) { // super.setPartPredicate(partPredicate); // return this; // } // // @Override // public RenderPassInformation setPartPredicate(Predicate<String> partPredicate) { // super.setPartPredicate(partPredicate); // return this; // } // // public RenderPassInformation setTextureTransform(Optional<Function<String, ResourceLocation>> textureRemap) { // return setTextureTransform(textureRemap.orElse(TRANSFORM_DIRECT)); // } // // public RenderPassInformation setTextureTransform(Function<String, ResourceLocation> textureRemap) { // this.textureRemap = Objects.requireNonNull(textureRemap); // return this; // } // } // Path: src/main/java/com/github/worldsender/mcanm/client/model/IEntityAnimator.java import com.github.worldsender.mcanm.client.model.util.RenderPassInformation; import net.minecraft.entity.EntityLiving; package com.github.worldsender.mcanm.client.model; public interface IEntityAnimator<T extends EntityLiving> { public static final IEntityAnimator<EntityLiving> STATIC_ANIMATOR = new IEntityAnimator<EntityLiving>() { @Override public IRenderPassInformation preRenderCallback( EntityLiving entity,
RenderPassInformation buffer,
WorldSEnder/MCAnm
src/main/java/com/github/worldsender/mcanm/MCAnm.java
// Path: src/main/java/com/github/worldsender/mcanm/client/config/MCAnmConfiguration.java // public class MCAnmConfiguration { // // private Configuration config; // private Property enableReload; // // public MCAnmConfiguration(File loadFile) { // config = new Configuration(loadFile); // config.load(); // enableReload = config.get(Configuration.CATEGORY_GENERAL, Reference.config_reload_enabled, true) // .setLanguageKey(Reference.gui_config_reload_enabled); // save(); // } // // public void onConfigChange(@SuppressWarnings("unused") OnConfigChangedEvent occe) { // save(); // } // // public void save() { // if (config.hasChanged()) // config.save(); // } // // public boolean isReloadEnabled() { // return this.enableReload.getBoolean(); // } // // public void addPropertiesToDisplayList(List<IConfigElement> list) { // list.add(new ConfigElement(enableReload)); // } // } // // Path: src/main/java/com/github/worldsender/mcanm/test/CubeEntity.java // public class CubeEntity extends EntityPig implements IAnimatedObject { // public static final IAnimation animation = CommonLoader // .loadAnimation(new ResourceLocation("mcanm:models/Cube/idle.mcanm")); // // public CubeEntity(World w) { // super(w); // } // // @Override // public RenderPassInformation preRenderCallback(float subFrame, RenderPassInformation callback) { // return callback.setAnimation(Optional.of(animation)).setFrame(this.ticksExisted % 90 + subFrame); // } // } // // Path: src/main/java/com/github/worldsender/mcanm/test/CubeEntityV2.java // public class CubeEntityV2 extends EntityPig { // public CubeEntityV2(World w) { // super(w); // } // }
import org.apache.logging.log4j.Logger; import com.github.worldsender.mcanm.client.config.MCAnmConfiguration; import com.github.worldsender.mcanm.test.CubeEntity; import com.github.worldsender.mcanm.test.CubeEntityV2; import net.minecraft.launchwrapper.Launch; import net.minecraft.util.ResourceLocation; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.client.event.ConfigChangedEvent.OnConfigChangedEvent; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.SidedProxy; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.registry.EntityRegistry;
package com.github.worldsender.mcanm; @Mod( modid = Reference.core_modid, name = Reference.core_modname, version = Reference.core_modversion, guiFactory = "com.github.worldsender.mcanm.client.config.MCAnmGuiFactory") public class MCAnm { /** * Enables various visual outputs, e.g. the bones of models are rendered. */ public static final boolean isDebug; static { Object deobfEnv = Launch.blackboard.get("fml.deobfuscatedEnvironment"); Boolean isDeobfEnv = deobfEnv instanceof Boolean ? (Boolean) deobfEnv : null; isDebug = isDeobfEnv == null ? false : isDeobfEnv.booleanValue(); } @Mod.Instance(Reference.core_modid) public static MCAnm instance; @SidedProxy( modId = Reference.core_modid, clientSide = "com.github.worldsender.mcanm.client.ClientProxy", serverSide = "com.github.worldsender.mcanm.server.ServerProxy") public static Proxy proxy;
// Path: src/main/java/com/github/worldsender/mcanm/client/config/MCAnmConfiguration.java // public class MCAnmConfiguration { // // private Configuration config; // private Property enableReload; // // public MCAnmConfiguration(File loadFile) { // config = new Configuration(loadFile); // config.load(); // enableReload = config.get(Configuration.CATEGORY_GENERAL, Reference.config_reload_enabled, true) // .setLanguageKey(Reference.gui_config_reload_enabled); // save(); // } // // public void onConfigChange(@SuppressWarnings("unused") OnConfigChangedEvent occe) { // save(); // } // // public void save() { // if (config.hasChanged()) // config.save(); // } // // public boolean isReloadEnabled() { // return this.enableReload.getBoolean(); // } // // public void addPropertiesToDisplayList(List<IConfigElement> list) { // list.add(new ConfigElement(enableReload)); // } // } // // Path: src/main/java/com/github/worldsender/mcanm/test/CubeEntity.java // public class CubeEntity extends EntityPig implements IAnimatedObject { // public static final IAnimation animation = CommonLoader // .loadAnimation(new ResourceLocation("mcanm:models/Cube/idle.mcanm")); // // public CubeEntity(World w) { // super(w); // } // // @Override // public RenderPassInformation preRenderCallback(float subFrame, RenderPassInformation callback) { // return callback.setAnimation(Optional.of(animation)).setFrame(this.ticksExisted % 90 + subFrame); // } // } // // Path: src/main/java/com/github/worldsender/mcanm/test/CubeEntityV2.java // public class CubeEntityV2 extends EntityPig { // public CubeEntityV2(World w) { // super(w); // } // } // Path: src/main/java/com/github/worldsender/mcanm/MCAnm.java import org.apache.logging.log4j.Logger; import com.github.worldsender.mcanm.client.config.MCAnmConfiguration; import com.github.worldsender.mcanm.test.CubeEntity; import com.github.worldsender.mcanm.test.CubeEntityV2; import net.minecraft.launchwrapper.Launch; import net.minecraft.util.ResourceLocation; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.client.event.ConfigChangedEvent.OnConfigChangedEvent; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.SidedProxy; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.registry.EntityRegistry; package com.github.worldsender.mcanm; @Mod( modid = Reference.core_modid, name = Reference.core_modname, version = Reference.core_modversion, guiFactory = "com.github.worldsender.mcanm.client.config.MCAnmGuiFactory") public class MCAnm { /** * Enables various visual outputs, e.g. the bones of models are rendered. */ public static final boolean isDebug; static { Object deobfEnv = Launch.blackboard.get("fml.deobfuscatedEnvironment"); Boolean isDeobfEnv = deobfEnv instanceof Boolean ? (Boolean) deobfEnv : null; isDebug = isDeobfEnv == null ? false : isDeobfEnv.booleanValue(); } @Mod.Instance(Reference.core_modid) public static MCAnm instance; @SidedProxy( modId = Reference.core_modid, clientSide = "com.github.worldsender.mcanm.client.ClientProxy", serverSide = "com.github.worldsender.mcanm.server.ServerProxy") public static Proxy proxy;
private MCAnmConfiguration config;
WorldSEnder/MCAnm
src/main/java/com/github/worldsender/mcanm/MCAnm.java
// Path: src/main/java/com/github/worldsender/mcanm/client/config/MCAnmConfiguration.java // public class MCAnmConfiguration { // // private Configuration config; // private Property enableReload; // // public MCAnmConfiguration(File loadFile) { // config = new Configuration(loadFile); // config.load(); // enableReload = config.get(Configuration.CATEGORY_GENERAL, Reference.config_reload_enabled, true) // .setLanguageKey(Reference.gui_config_reload_enabled); // save(); // } // // public void onConfigChange(@SuppressWarnings("unused") OnConfigChangedEvent occe) { // save(); // } // // public void save() { // if (config.hasChanged()) // config.save(); // } // // public boolean isReloadEnabled() { // return this.enableReload.getBoolean(); // } // // public void addPropertiesToDisplayList(List<IConfigElement> list) { // list.add(new ConfigElement(enableReload)); // } // } // // Path: src/main/java/com/github/worldsender/mcanm/test/CubeEntity.java // public class CubeEntity extends EntityPig implements IAnimatedObject { // public static final IAnimation animation = CommonLoader // .loadAnimation(new ResourceLocation("mcanm:models/Cube/idle.mcanm")); // // public CubeEntity(World w) { // super(w); // } // // @Override // public RenderPassInformation preRenderCallback(float subFrame, RenderPassInformation callback) { // return callback.setAnimation(Optional.of(animation)).setFrame(this.ticksExisted % 90 + subFrame); // } // } // // Path: src/main/java/com/github/worldsender/mcanm/test/CubeEntityV2.java // public class CubeEntityV2 extends EntityPig { // public CubeEntityV2(World w) { // super(w); // } // }
import org.apache.logging.log4j.Logger; import com.github.worldsender.mcanm.client.config.MCAnmConfiguration; import com.github.worldsender.mcanm.test.CubeEntity; import com.github.worldsender.mcanm.test.CubeEntityV2; import net.minecraft.launchwrapper.Launch; import net.minecraft.util.ResourceLocation; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.client.event.ConfigChangedEvent.OnConfigChangedEvent; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.SidedProxy; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.registry.EntityRegistry;
Boolean isDeobfEnv = deobfEnv instanceof Boolean ? (Boolean) deobfEnv : null; isDebug = isDeobfEnv == null ? false : isDeobfEnv.booleanValue(); } @Mod.Instance(Reference.core_modid) public static MCAnm instance; @SidedProxy( modId = Reference.core_modid, clientSide = "com.github.worldsender.mcanm.client.ClientProxy", serverSide = "com.github.worldsender.mcanm.server.ServerProxy") public static Proxy proxy; private MCAnmConfiguration config; private Logger logger; @Mod.EventHandler public void preInit(FMLPreInitializationEvent pre) { logger = pre.getModLog(); config = new MCAnmConfiguration(pre.getSuggestedConfigurationFile()); proxy.preInit(); MinecraftForge.EVENT_BUS.register(this); logger.info("Successfully loaded MC Animations"); } @Mod.EventHandler public void init(@SuppressWarnings("unused") FMLInitializationEvent event) { if (isDebug) { ResourceLocation ID_CUBE = new ResourceLocation("mcanm:cube"); ResourceLocation ID_CUBE_V2 = new ResourceLocation("mcanm:cube2");
// Path: src/main/java/com/github/worldsender/mcanm/client/config/MCAnmConfiguration.java // public class MCAnmConfiguration { // // private Configuration config; // private Property enableReload; // // public MCAnmConfiguration(File loadFile) { // config = new Configuration(loadFile); // config.load(); // enableReload = config.get(Configuration.CATEGORY_GENERAL, Reference.config_reload_enabled, true) // .setLanguageKey(Reference.gui_config_reload_enabled); // save(); // } // // public void onConfigChange(@SuppressWarnings("unused") OnConfigChangedEvent occe) { // save(); // } // // public void save() { // if (config.hasChanged()) // config.save(); // } // // public boolean isReloadEnabled() { // return this.enableReload.getBoolean(); // } // // public void addPropertiesToDisplayList(List<IConfigElement> list) { // list.add(new ConfigElement(enableReload)); // } // } // // Path: src/main/java/com/github/worldsender/mcanm/test/CubeEntity.java // public class CubeEntity extends EntityPig implements IAnimatedObject { // public static final IAnimation animation = CommonLoader // .loadAnimation(new ResourceLocation("mcanm:models/Cube/idle.mcanm")); // // public CubeEntity(World w) { // super(w); // } // // @Override // public RenderPassInformation preRenderCallback(float subFrame, RenderPassInformation callback) { // return callback.setAnimation(Optional.of(animation)).setFrame(this.ticksExisted % 90 + subFrame); // } // } // // Path: src/main/java/com/github/worldsender/mcanm/test/CubeEntityV2.java // public class CubeEntityV2 extends EntityPig { // public CubeEntityV2(World w) { // super(w); // } // } // Path: src/main/java/com/github/worldsender/mcanm/MCAnm.java import org.apache.logging.log4j.Logger; import com.github.worldsender.mcanm.client.config.MCAnmConfiguration; import com.github.worldsender.mcanm.test.CubeEntity; import com.github.worldsender.mcanm.test.CubeEntityV2; import net.minecraft.launchwrapper.Launch; import net.minecraft.util.ResourceLocation; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.client.event.ConfigChangedEvent.OnConfigChangedEvent; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.SidedProxy; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.registry.EntityRegistry; Boolean isDeobfEnv = deobfEnv instanceof Boolean ? (Boolean) deobfEnv : null; isDebug = isDeobfEnv == null ? false : isDeobfEnv.booleanValue(); } @Mod.Instance(Reference.core_modid) public static MCAnm instance; @SidedProxy( modId = Reference.core_modid, clientSide = "com.github.worldsender.mcanm.client.ClientProxy", serverSide = "com.github.worldsender.mcanm.server.ServerProxy") public static Proxy proxy; private MCAnmConfiguration config; private Logger logger; @Mod.EventHandler public void preInit(FMLPreInitializationEvent pre) { logger = pre.getModLog(); config = new MCAnmConfiguration(pre.getSuggestedConfigurationFile()); proxy.preInit(); MinecraftForge.EVENT_BUS.register(this); logger.info("Successfully loaded MC Animations"); } @Mod.EventHandler public void init(@SuppressWarnings("unused") FMLInitializationEvent event) { if (isDebug) { ResourceLocation ID_CUBE = new ResourceLocation("mcanm:cube"); ResourceLocation ID_CUBE_V2 = new ResourceLocation("mcanm:cube2");
EntityRegistry.registerModEntity(ID_CUBE, CubeEntity.class, "Cube", 0, this, 80, 1, true);
WorldSEnder/MCAnm
src/main/java/com/github/worldsender/mcanm/MCAnm.java
// Path: src/main/java/com/github/worldsender/mcanm/client/config/MCAnmConfiguration.java // public class MCAnmConfiguration { // // private Configuration config; // private Property enableReload; // // public MCAnmConfiguration(File loadFile) { // config = new Configuration(loadFile); // config.load(); // enableReload = config.get(Configuration.CATEGORY_GENERAL, Reference.config_reload_enabled, true) // .setLanguageKey(Reference.gui_config_reload_enabled); // save(); // } // // public void onConfigChange(@SuppressWarnings("unused") OnConfigChangedEvent occe) { // save(); // } // // public void save() { // if (config.hasChanged()) // config.save(); // } // // public boolean isReloadEnabled() { // return this.enableReload.getBoolean(); // } // // public void addPropertiesToDisplayList(List<IConfigElement> list) { // list.add(new ConfigElement(enableReload)); // } // } // // Path: src/main/java/com/github/worldsender/mcanm/test/CubeEntity.java // public class CubeEntity extends EntityPig implements IAnimatedObject { // public static final IAnimation animation = CommonLoader // .loadAnimation(new ResourceLocation("mcanm:models/Cube/idle.mcanm")); // // public CubeEntity(World w) { // super(w); // } // // @Override // public RenderPassInformation preRenderCallback(float subFrame, RenderPassInformation callback) { // return callback.setAnimation(Optional.of(animation)).setFrame(this.ticksExisted % 90 + subFrame); // } // } // // Path: src/main/java/com/github/worldsender/mcanm/test/CubeEntityV2.java // public class CubeEntityV2 extends EntityPig { // public CubeEntityV2(World w) { // super(w); // } // }
import org.apache.logging.log4j.Logger; import com.github.worldsender.mcanm.client.config.MCAnmConfiguration; import com.github.worldsender.mcanm.test.CubeEntity; import com.github.worldsender.mcanm.test.CubeEntityV2; import net.minecraft.launchwrapper.Launch; import net.minecraft.util.ResourceLocation; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.client.event.ConfigChangedEvent.OnConfigChangedEvent; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.SidedProxy; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.registry.EntityRegistry;
isDebug = isDeobfEnv == null ? false : isDeobfEnv.booleanValue(); } @Mod.Instance(Reference.core_modid) public static MCAnm instance; @SidedProxy( modId = Reference.core_modid, clientSide = "com.github.worldsender.mcanm.client.ClientProxy", serverSide = "com.github.worldsender.mcanm.server.ServerProxy") public static Proxy proxy; private MCAnmConfiguration config; private Logger logger; @Mod.EventHandler public void preInit(FMLPreInitializationEvent pre) { logger = pre.getModLog(); config = new MCAnmConfiguration(pre.getSuggestedConfigurationFile()); proxy.preInit(); MinecraftForge.EVENT_BUS.register(this); logger.info("Successfully loaded MC Animations"); } @Mod.EventHandler public void init(@SuppressWarnings("unused") FMLInitializationEvent event) { if (isDebug) { ResourceLocation ID_CUBE = new ResourceLocation("mcanm:cube"); ResourceLocation ID_CUBE_V2 = new ResourceLocation("mcanm:cube2"); EntityRegistry.registerModEntity(ID_CUBE, CubeEntity.class, "Cube", 0, this, 80, 1, true);
// Path: src/main/java/com/github/worldsender/mcanm/client/config/MCAnmConfiguration.java // public class MCAnmConfiguration { // // private Configuration config; // private Property enableReload; // // public MCAnmConfiguration(File loadFile) { // config = new Configuration(loadFile); // config.load(); // enableReload = config.get(Configuration.CATEGORY_GENERAL, Reference.config_reload_enabled, true) // .setLanguageKey(Reference.gui_config_reload_enabled); // save(); // } // // public void onConfigChange(@SuppressWarnings("unused") OnConfigChangedEvent occe) { // save(); // } // // public void save() { // if (config.hasChanged()) // config.save(); // } // // public boolean isReloadEnabled() { // return this.enableReload.getBoolean(); // } // // public void addPropertiesToDisplayList(List<IConfigElement> list) { // list.add(new ConfigElement(enableReload)); // } // } // // Path: src/main/java/com/github/worldsender/mcanm/test/CubeEntity.java // public class CubeEntity extends EntityPig implements IAnimatedObject { // public static final IAnimation animation = CommonLoader // .loadAnimation(new ResourceLocation("mcanm:models/Cube/idle.mcanm")); // // public CubeEntity(World w) { // super(w); // } // // @Override // public RenderPassInformation preRenderCallback(float subFrame, RenderPassInformation callback) { // return callback.setAnimation(Optional.of(animation)).setFrame(this.ticksExisted % 90 + subFrame); // } // } // // Path: src/main/java/com/github/worldsender/mcanm/test/CubeEntityV2.java // public class CubeEntityV2 extends EntityPig { // public CubeEntityV2(World w) { // super(w); // } // } // Path: src/main/java/com/github/worldsender/mcanm/MCAnm.java import org.apache.logging.log4j.Logger; import com.github.worldsender.mcanm.client.config.MCAnmConfiguration; import com.github.worldsender.mcanm.test.CubeEntity; import com.github.worldsender.mcanm.test.CubeEntityV2; import net.minecraft.launchwrapper.Launch; import net.minecraft.util.ResourceLocation; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.client.event.ConfigChangedEvent.OnConfigChangedEvent; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.SidedProxy; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.registry.EntityRegistry; isDebug = isDeobfEnv == null ? false : isDeobfEnv.booleanValue(); } @Mod.Instance(Reference.core_modid) public static MCAnm instance; @SidedProxy( modId = Reference.core_modid, clientSide = "com.github.worldsender.mcanm.client.ClientProxy", serverSide = "com.github.worldsender.mcanm.server.ServerProxy") public static Proxy proxy; private MCAnmConfiguration config; private Logger logger; @Mod.EventHandler public void preInit(FMLPreInitializationEvent pre) { logger = pre.getModLog(); config = new MCAnmConfiguration(pre.getSuggestedConfigurationFile()); proxy.preInit(); MinecraftForge.EVENT_BUS.register(this); logger.info("Successfully loaded MC Animations"); } @Mod.EventHandler public void init(@SuppressWarnings("unused") FMLInitializationEvent event) { if (isDebug) { ResourceLocation ID_CUBE = new ResourceLocation("mcanm:cube"); ResourceLocation ID_CUBE_V2 = new ResourceLocation("mcanm:cube2"); EntityRegistry.registerModEntity(ID_CUBE, CubeEntity.class, "Cube", 0, this, 80, 1, true);
EntityRegistry.registerModEntity(ID_CUBE_V2, CubeEntityV2.class, "CubeV2", 1, this, 80, 1, true);
WorldSEnder/MCAnm
src/main/java/com/github/worldsender/mcanm/common/animation/parts/AnimatedValue.java
// Path: src/main/java/com/github/worldsender/mcanm/common/exceptions/ModelFormatException.java // public class ModelFormatException extends IllegalArgumentException { // /** // * // */ // private static final long serialVersionUID = -4000239134878464297L; // // public ModelFormatException() { // super(); // } // // public ModelFormatException(String message) { // super(message); // } // // public ModelFormatException(Throwable cause) { // super(cause); // } // // public ModelFormatException(String message, Throwable cause) { // super(message, cause); // } // }
import java.io.DataInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.lwjgl.util.vector.Vector2f; import com.github.worldsender.mcanm.common.exceptions.ModelFormatException;
package com.github.worldsender.mcanm.common.animation.parts; public class AnimatedValue { public static class AnimatedValueBuilder { private AnimatedValue value = null; private void checkAvailable() { value = new AnimatedValue(0.0f); } public AnimatedValueBuilder addSpline(Spline spline) { value.splines.add(spline); return this; }
// Path: src/main/java/com/github/worldsender/mcanm/common/exceptions/ModelFormatException.java // public class ModelFormatException extends IllegalArgumentException { // /** // * // */ // private static final long serialVersionUID = -4000239134878464297L; // // public ModelFormatException() { // super(); // } // // public ModelFormatException(String message) { // super(message); // } // // public ModelFormatException(Throwable cause) { // super(cause); // } // // public ModelFormatException(String message, Throwable cause) { // super(message, cause); // } // } // Path: src/main/java/com/github/worldsender/mcanm/common/animation/parts/AnimatedValue.java import java.io.DataInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.lwjgl.util.vector.Vector2f; import com.github.worldsender.mcanm.common.exceptions.ModelFormatException; package com.github.worldsender.mcanm.common.animation.parts; public class AnimatedValue { public static class AnimatedValueBuilder { private AnimatedValue value = null; private void checkAvailable() { value = new AnimatedValue(0.0f); } public AnimatedValueBuilder addSpline(Spline spline) { value.splines.add(spline); return this; }
public AnimatedValueBuilder fromStream(DataInputStream dis) throws IOException, ModelFormatException {
WorldSEnder/MCAnm
src/main/java/com/github/worldsender/mcanm/client/model/util/ModelStateInformation.java
// Path: src/main/java/com/github/worldsender/mcanm/client/model/IModelStateInformation.java // public interface IModelStateInformation { // // IAnimation getAnimation(); // // float getFrame(); // // boolean shouldRenderPart(String part); // // } // // Path: src/main/java/com/github/worldsender/mcanm/common/animation/IAnimation.java // public interface IAnimation { // /** // * Describes a BoneTransformation, including rotation, translation and scaling. This class is opaque i.e. all // * getters and setters don't make defensive copies and states can be manipulated from the outside. // * // * @author WorldSEnder // * // */ // public static class BoneTransformation { // public static final BoneTransformation identity = new BoneTransformation(); // // private static Vector3f identityScale() { // return new Vector3f(1.0F, 1.0F, 1.0F); // } // // public final Matrix4f matrix; // // public BoneTransformation() { // this(null, null, null); // } // // public BoneTransformation(Vector3f translation, Quat4f quat) { // this(translation, quat, identityScale()); // } // // public BoneTransformation(Vector3f translation, Quat4f quat, Vector3f scale) { // if (quat == null) // quat = new Quat4f(); // if (translation == null) // translation = new Vector3f(); // if (scale == null) // scale = identityScale(); // this.matrix = Utils.fromRTS(quat, translation, scale, new Matrix4f()); // } // // public Matrix4f getMatrix() { // return matrix; // } // } // // /** // * Stores the bone's current {@link BoneTransformation} in transform(identified by name). <br> // * If the requested bone is not known to the animation transform is left untouched and this return // * <code>false</code>. Otherwise transform is set to the bone's current transform state. // * // * @param bone // * the name of the bone the matrix is requested // * @param frame // * the current frame in the animation // * @param transform // * the transform to set // * @return if a transformation has been set // */ // public boolean storeCurrentTransformation(String bone, float frame, BoneTransformation transform); // }
import java.util.Objects; import java.util.Optional; import java.util.function.Predicate; import com.github.worldsender.mcanm.client.model.IModelStateInformation; import com.github.worldsender.mcanm.common.animation.IAnimation;
package com.github.worldsender.mcanm.client.model.util; public class ModelStateInformation implements IModelStateInformation { /** * A suitable {@link Predicate} to return in {@link #getPartPredicate(float)} to render all parts without exception. * Note that this will not test if the currently executed animation wants to display the part. */ public static final Predicate<String> RENDER_ALL = g -> true; /** * A suitable {@link Predicate} to return in {@link #getPartPredicate(float)} to render no parts without exception. * Note that this will not test if the currently executed animation wants to display the part. */ public static final Predicate<String> RENDER_NONE = g -> false; /** * This is a default animation that never returns a pose for any bone it is asked for. */
// Path: src/main/java/com/github/worldsender/mcanm/client/model/IModelStateInformation.java // public interface IModelStateInformation { // // IAnimation getAnimation(); // // float getFrame(); // // boolean shouldRenderPart(String part); // // } // // Path: src/main/java/com/github/worldsender/mcanm/common/animation/IAnimation.java // public interface IAnimation { // /** // * Describes a BoneTransformation, including rotation, translation and scaling. This class is opaque i.e. all // * getters and setters don't make defensive copies and states can be manipulated from the outside. // * // * @author WorldSEnder // * // */ // public static class BoneTransformation { // public static final BoneTransformation identity = new BoneTransformation(); // // private static Vector3f identityScale() { // return new Vector3f(1.0F, 1.0F, 1.0F); // } // // public final Matrix4f matrix; // // public BoneTransformation() { // this(null, null, null); // } // // public BoneTransformation(Vector3f translation, Quat4f quat) { // this(translation, quat, identityScale()); // } // // public BoneTransformation(Vector3f translation, Quat4f quat, Vector3f scale) { // if (quat == null) // quat = new Quat4f(); // if (translation == null) // translation = new Vector3f(); // if (scale == null) // scale = identityScale(); // this.matrix = Utils.fromRTS(quat, translation, scale, new Matrix4f()); // } // // public Matrix4f getMatrix() { // return matrix; // } // } // // /** // * Stores the bone's current {@link BoneTransformation} in transform(identified by name). <br> // * If the requested bone is not known to the animation transform is left untouched and this return // * <code>false</code>. Otherwise transform is set to the bone's current transform state. // * // * @param bone // * the name of the bone the matrix is requested // * @param frame // * the current frame in the animation // * @param transform // * the transform to set // * @return if a transformation has been set // */ // public boolean storeCurrentTransformation(String bone, float frame, BoneTransformation transform); // } // Path: src/main/java/com/github/worldsender/mcanm/client/model/util/ModelStateInformation.java import java.util.Objects; import java.util.Optional; import java.util.function.Predicate; import com.github.worldsender.mcanm.client.model.IModelStateInformation; import com.github.worldsender.mcanm.common.animation.IAnimation; package com.github.worldsender.mcanm.client.model.util; public class ModelStateInformation implements IModelStateInformation { /** * A suitable {@link Predicate} to return in {@link #getPartPredicate(float)} to render all parts without exception. * Note that this will not test if the currently executed animation wants to display the part. */ public static final Predicate<String> RENDER_ALL = g -> true; /** * A suitable {@link Predicate} to return in {@link #getPartPredicate(float)} to render no parts without exception. * Note that this will not test if the currently executed animation wants to display the part. */ public static final Predicate<String> RENDER_NONE = g -> false; /** * This is a default animation that never returns a pose for any bone it is asked for. */
public static final IAnimation BIND_POSE = new IAnimation() {
WorldSEnder/MCAnm
src/main/java/com/github/worldsender/mcanm/client/mcanmmodel/stored/parts/ModelPartV1.java
// Path: src/main/java/com/github/worldsender/mcanm/client/mcanmmodel/visitor/TesselationPoint.java // public class TesselationPoint { // public Vector3f coords; // public Vector3f normal; // public Vector2f texCoords; // public BoneBinding[] boneBindings; // // public static TesselationPoint readFrom(DataInputStream di) throws IOException { // TesselationPoint tessP = new TesselationPoint(); // // Read coords // Vector3f coords = Utils.readVector3f(di); // // Read normal // Vector3f normal = Utils.readVector3f(di); // if (normal.length() == 0) // throw new ModelFormatException("Normal vector can't have zerolength."); // // Read materialIndex coordinates // Vector2f texCoords = Utils.readVector2f(di); // // Read bindings // BoneBinding[] bindings = BoneBinding.readMultipleFrom(di); // // Apply attributes // tessP.coords = coords; // tessP.normal = normal; // tessP.texCoords = texCoords; // tessP.boneBindings = bindings; // return tessP; // } // }
import com.github.worldsender.mcanm.client.mcanmmodel.visitor.TesselationPoint;
package com.github.worldsender.mcanm.client.mcanmmodel.stored.parts; public class ModelPartV1 { public String name; /** All available {@link TesselationPoint}s in this part of the model */
// Path: src/main/java/com/github/worldsender/mcanm/client/mcanmmodel/visitor/TesselationPoint.java // public class TesselationPoint { // public Vector3f coords; // public Vector3f normal; // public Vector2f texCoords; // public BoneBinding[] boneBindings; // // public static TesselationPoint readFrom(DataInputStream di) throws IOException { // TesselationPoint tessP = new TesselationPoint(); // // Read coords // Vector3f coords = Utils.readVector3f(di); // // Read normal // Vector3f normal = Utils.readVector3f(di); // if (normal.length() == 0) // throw new ModelFormatException("Normal vector can't have zerolength."); // // Read materialIndex coordinates // Vector2f texCoords = Utils.readVector2f(di); // // Read bindings // BoneBinding[] bindings = BoneBinding.readMultipleFrom(di); // // Apply attributes // tessP.coords = coords; // tessP.normal = normal; // tessP.texCoords = texCoords; // tessP.boneBindings = bindings; // return tessP; // } // } // Path: src/main/java/com/github/worldsender/mcanm/client/mcanmmodel/stored/parts/ModelPartV1.java import com.github.worldsender.mcanm.client.mcanmmodel.visitor.TesselationPoint; package com.github.worldsender.mcanm.client.mcanmmodel.stored.parts; public class ModelPartV1 { public String name; /** All available {@link TesselationPoint}s in this part of the model */
public TesselationPoint[] points;
WorldSEnder/MCAnm
src/main/java/com/github/worldsender/mcanm/client/mcanmmodel/parts/Vertex.java
// Path: src/main/java/com/github/worldsender/mcanm/client/renderer/ITesselator.java // public interface ITesselator { // // void setTextureUV(double u, double v); // // void setNormal(float x, float y, float z); // // void addVertex(double x, double y, double z); // }
import javax.vecmath.Point2f; import javax.vecmath.Point4f; import javax.vecmath.Tuple2f; import javax.vecmath.Tuple3f; import javax.vecmath.Tuple4f; import javax.vecmath.Vector3f; import javax.vecmath.Vector4f; import com.github.worldsender.mcanm.client.renderer.ITesselator; import net.minecraft.client.renderer.Tessellator;
package com.github.worldsender.mcanm.client.mcanmmodel.parts; public class Vertex { private Point4f pos; private Vector3f norm; private Point2f uv; public Vertex(Tuple4f pos, Tuple3f norm, Tuple2f uv) { this.pos = new Point4f(pos); this.norm = new Vector3f(norm); this.uv = new Point2f(uv); } public Vertex(Vertex copyFrom) { this.pos = new Point4f(copyFrom.pos); this.norm = new Vector3f(copyFrom.norm); this.uv = new Point2f(copyFrom.uv); } /** * Uses the {@link Tessellator} to draw the model. Take care that the Tessellator is already drawing. */
// Path: src/main/java/com/github/worldsender/mcanm/client/renderer/ITesselator.java // public interface ITesselator { // // void setTextureUV(double u, double v); // // void setNormal(float x, float y, float z); // // void addVertex(double x, double y, double z); // } // Path: src/main/java/com/github/worldsender/mcanm/client/mcanmmodel/parts/Vertex.java import javax.vecmath.Point2f; import javax.vecmath.Point4f; import javax.vecmath.Tuple2f; import javax.vecmath.Tuple3f; import javax.vecmath.Tuple4f; import javax.vecmath.Vector3f; import javax.vecmath.Vector4f; import com.github.worldsender.mcanm.client.renderer.ITesselator; import net.minecraft.client.renderer.Tessellator; package com.github.worldsender.mcanm.client.mcanmmodel.parts; public class Vertex { private Point4f pos; private Vector3f norm; private Point2f uv; public Vertex(Tuple4f pos, Tuple3f norm, Tuple2f uv) { this.pos = new Point4f(pos); this.norm = new Vector3f(norm); this.uv = new Point2f(uv); } public Vertex(Vertex copyFrom) { this.pos = new Point4f(copyFrom.pos); this.norm = new Vector3f(copyFrom.norm); this.uv = new Point2f(copyFrom.uv); } /** * Uses the {@link Tessellator} to draw the model. Take care that the Tessellator is already drawing. */
public void render(ITesselator renderer) {
WorldSEnder/MCAnm
src/main/java/com/github/worldsender/mcanm/client/model/util/RenderPassInformation.java
// Path: src/main/java/com/github/worldsender/mcanm/client/model/IRenderPassInformation.java // public interface IRenderPassInformation extends IModelStateInformation { // /** // * Retrieves the texture that should go into the texture slot slot // * // * @param slot // * the name of the texture slot getting polled // * @return the resource location of the texture to stick // */ // ResourceLocation getActualResourceLocation(String slot); // } // // Path: src/main/java/com/github/worldsender/mcanm/common/animation/IAnimation.java // public interface IAnimation { // /** // * Describes a BoneTransformation, including rotation, translation and scaling. This class is opaque i.e. all // * getters and setters don't make defensive copies and states can be manipulated from the outside. // * // * @author WorldSEnder // * // */ // public static class BoneTransformation { // public static final BoneTransformation identity = new BoneTransformation(); // // private static Vector3f identityScale() { // return new Vector3f(1.0F, 1.0F, 1.0F); // } // // public final Matrix4f matrix; // // public BoneTransformation() { // this(null, null, null); // } // // public BoneTransformation(Vector3f translation, Quat4f quat) { // this(translation, quat, identityScale()); // } // // public BoneTransformation(Vector3f translation, Quat4f quat, Vector3f scale) { // if (quat == null) // quat = new Quat4f(); // if (translation == null) // translation = new Vector3f(); // if (scale == null) // scale = identityScale(); // this.matrix = Utils.fromRTS(quat, translation, scale, new Matrix4f()); // } // // public Matrix4f getMatrix() { // return matrix; // } // } // // /** // * Stores the bone's current {@link BoneTransformation} in transform(identified by name). <br> // * If the requested bone is not known to the animation transform is left untouched and this return // * <code>false</code>. Otherwise transform is set to the bone's current transform state. // * // * @param bone // * the name of the bone the matrix is requested // * @param frame // * the current frame in the animation // * @param transform // * the transform to set // * @return if a transformation has been set // */ // public boolean storeCurrentTransformation(String bone, float frame, BoneTransformation transform); // }
import java.util.Objects; import java.util.Optional; import java.util.function.Function; import java.util.function.Predicate; import com.github.worldsender.mcanm.client.model.IRenderPassInformation; import com.github.worldsender.mcanm.common.animation.IAnimation; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import net.minecraft.util.ResourceLocation;
package com.github.worldsender.mcanm.client.model.util; /** * Used to simplify the pre-render callback process. This class is an aggregate of all needed information for one render * pass (aka. rendering one object). You may use the setter methods or simply extend the class and override the getter * methods to return what you need.<br> * You should not call new RenderPassInformation(...) every time one is needed but reuse instances you used before. The * internal API doesn't keep custom instances around after the render-pass is over, only its own. * * @author WorldSEnder * */ public class RenderPassInformation extends ModelStateInformation implements IRenderPassInformation { public static final Function<String, ResourceLocation> makeCachingTransform( Function<String, ResourceLocation> cacheLoader) { LoadingCache<String, ResourceLocation> cachedResourceLoc = CacheBuilder.newBuilder().maximumSize(100) .build(new CacheLoader<String, ResourceLocation>() { @Override public ResourceLocation load(String key) { return cacheLoader.apply(key); } }); return cachedResourceLoc::getUnchecked; } public static final Function<String, ResourceLocation> TRANSFORM_DIRECT = makeCachingTransform( ResourceLocation::new); /** * This is the default texture rebinding, it just returns the given resource-location and as such does not change * the bound texture. */ public static final Function<ResourceLocation, ResourceLocation> IDENTITY = Function.identity(); private Function<String, ResourceLocation> textureRemap; public RenderPassInformation() { this.reset(); } public RenderPassInformation( float frame,
// Path: src/main/java/com/github/worldsender/mcanm/client/model/IRenderPassInformation.java // public interface IRenderPassInformation extends IModelStateInformation { // /** // * Retrieves the texture that should go into the texture slot slot // * // * @param slot // * the name of the texture slot getting polled // * @return the resource location of the texture to stick // */ // ResourceLocation getActualResourceLocation(String slot); // } // // Path: src/main/java/com/github/worldsender/mcanm/common/animation/IAnimation.java // public interface IAnimation { // /** // * Describes a BoneTransformation, including rotation, translation and scaling. This class is opaque i.e. all // * getters and setters don't make defensive copies and states can be manipulated from the outside. // * // * @author WorldSEnder // * // */ // public static class BoneTransformation { // public static final BoneTransformation identity = new BoneTransformation(); // // private static Vector3f identityScale() { // return new Vector3f(1.0F, 1.0F, 1.0F); // } // // public final Matrix4f matrix; // // public BoneTransformation() { // this(null, null, null); // } // // public BoneTransformation(Vector3f translation, Quat4f quat) { // this(translation, quat, identityScale()); // } // // public BoneTransformation(Vector3f translation, Quat4f quat, Vector3f scale) { // if (quat == null) // quat = new Quat4f(); // if (translation == null) // translation = new Vector3f(); // if (scale == null) // scale = identityScale(); // this.matrix = Utils.fromRTS(quat, translation, scale, new Matrix4f()); // } // // public Matrix4f getMatrix() { // return matrix; // } // } // // /** // * Stores the bone's current {@link BoneTransformation} in transform(identified by name). <br> // * If the requested bone is not known to the animation transform is left untouched and this return // * <code>false</code>. Otherwise transform is set to the bone's current transform state. // * // * @param bone // * the name of the bone the matrix is requested // * @param frame // * the current frame in the animation // * @param transform // * the transform to set // * @return if a transformation has been set // */ // public boolean storeCurrentTransformation(String bone, float frame, BoneTransformation transform); // } // Path: src/main/java/com/github/worldsender/mcanm/client/model/util/RenderPassInformation.java import java.util.Objects; import java.util.Optional; import java.util.function.Function; import java.util.function.Predicate; import com.github.worldsender.mcanm.client.model.IRenderPassInformation; import com.github.worldsender.mcanm.common.animation.IAnimation; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import net.minecraft.util.ResourceLocation; package com.github.worldsender.mcanm.client.model.util; /** * Used to simplify the pre-render callback process. This class is an aggregate of all needed information for one render * pass (aka. rendering one object). You may use the setter methods or simply extend the class and override the getter * methods to return what you need.<br> * You should not call new RenderPassInformation(...) every time one is needed but reuse instances you used before. The * internal API doesn't keep custom instances around after the render-pass is over, only its own. * * @author WorldSEnder * */ public class RenderPassInformation extends ModelStateInformation implements IRenderPassInformation { public static final Function<String, ResourceLocation> makeCachingTransform( Function<String, ResourceLocation> cacheLoader) { LoadingCache<String, ResourceLocation> cachedResourceLoc = CacheBuilder.newBuilder().maximumSize(100) .build(new CacheLoader<String, ResourceLocation>() { @Override public ResourceLocation load(String key) { return cacheLoader.apply(key); } }); return cachedResourceLoc::getUnchecked; } public static final Function<String, ResourceLocation> TRANSFORM_DIRECT = makeCachingTransform( ResourceLocation::new); /** * This is the default texture rebinding, it just returns the given resource-location and as such does not change * the bound texture. */ public static final Function<ResourceLocation, ResourceLocation> IDENTITY = Function.identity(); private Function<String, ResourceLocation> textureRemap; public RenderPassInformation() { this.reset(); } public RenderPassInformation( float frame,
Optional<IAnimation> animation,
WorldSEnder/MCAnm
src/main/java/com/github/worldsender/mcanm/client/model/ModelAnimated.java
// Path: src/main/java/com/github/worldsender/mcanm/client/IRenderPass.java // public interface IRenderPass extends IRenderPassInformation { // /** // * Binds the resource-location given.<br> // * <b>WARNING</b> This does not transform the resourc-location via // * {@link #getActualResourceLocation(ResourceLocation)}. This has the be done before calling this method. // * // * @param resLoc // * the resource to bind // */ // void bindTexture(ResourceLocation resLoc); // } // // Path: src/main/java/com/github/worldsender/mcanm/client/mcanmmodel/IModel.java // public interface IModel { // void render(IRenderPass renderPass); // }
import com.github.worldsender.mcanm.client.IRenderPass; import com.github.worldsender.mcanm.client.mcanmmodel.IModel; import net.minecraft.client.model.ModelBase; import net.minecraft.client.model.ModelRenderer; import net.minecraft.client.model.TextureOffset; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.entity.Entity;
package com.github.worldsender.mcanm.client.model; /** * A general purpose model that should fulfill most of your needs. It is possible to use an {@link IEntityAnimator} to * determine the rendered * * @author WorldSEnder * */ public class ModelAnimated extends ModelBase { private IModel model;
// Path: src/main/java/com/github/worldsender/mcanm/client/IRenderPass.java // public interface IRenderPass extends IRenderPassInformation { // /** // * Binds the resource-location given.<br> // * <b>WARNING</b> This does not transform the resourc-location via // * {@link #getActualResourceLocation(ResourceLocation)}. This has the be done before calling this method. // * // * @param resLoc // * the resource to bind // */ // void bindTexture(ResourceLocation resLoc); // } // // Path: src/main/java/com/github/worldsender/mcanm/client/mcanmmodel/IModel.java // public interface IModel { // void render(IRenderPass renderPass); // } // Path: src/main/java/com/github/worldsender/mcanm/client/model/ModelAnimated.java import com.github.worldsender.mcanm.client.IRenderPass; import com.github.worldsender.mcanm.client.mcanmmodel.IModel; import net.minecraft.client.model.ModelBase; import net.minecraft.client.model.ModelRenderer; import net.minecraft.client.model.TextureOffset; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.entity.Entity; package com.github.worldsender.mcanm.client.model; /** * A general purpose model that should fulfill most of your needs. It is possible to use an {@link IEntityAnimator} to * determine the rendered * * @author WorldSEnder * */ public class ModelAnimated extends ModelBase { private IModel model;
private IRenderPass renderPass;
WorldSEnder/MCAnm
src/main/java/com/github/worldsender/mcanm/client/config/MCAnmConfiguration.java
// Path: src/main/java/com/github/worldsender/mcanm/Reference.java // public class Reference { // // public static final String config_reload_enabled = "enableReload"; // public static final String gui_config_title = "mcanm.config.title"; // public static final String gui_config_reload_enabled = "mcanm.config.autoreload"; // public static final String[] model_suffix_list = { ".mhmd" }; // public static final String model_type = "model_type"; // // public static final String core_modid = "@modid@"; // public static final String core_modname = "@MODNAME@"; // public static final String core_modversion = "@VERSION@"; // }
import java.io.File; import java.util.List; import com.github.worldsender.mcanm.Reference; import net.minecraftforge.common.config.ConfigElement; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.common.config.Property; import net.minecraftforge.fml.client.config.IConfigElement; import net.minecraftforge.fml.client.event.ConfigChangedEvent.OnConfigChangedEvent;
package com.github.worldsender.mcanm.client.config; public class MCAnmConfiguration { private Configuration config; private Property enableReload; public MCAnmConfiguration(File loadFile) { config = new Configuration(loadFile); config.load();
// Path: src/main/java/com/github/worldsender/mcanm/Reference.java // public class Reference { // // public static final String config_reload_enabled = "enableReload"; // public static final String gui_config_title = "mcanm.config.title"; // public static final String gui_config_reload_enabled = "mcanm.config.autoreload"; // public static final String[] model_suffix_list = { ".mhmd" }; // public static final String model_type = "model_type"; // // public static final String core_modid = "@modid@"; // public static final String core_modname = "@MODNAME@"; // public static final String core_modversion = "@VERSION@"; // } // Path: src/main/java/com/github/worldsender/mcanm/client/config/MCAnmConfiguration.java import java.io.File; import java.util.List; import com.github.worldsender.mcanm.Reference; import net.minecraftforge.common.config.ConfigElement; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.common.config.Property; import net.minecraftforge.fml.client.config.IConfigElement; import net.minecraftforge.fml.client.event.ConfigChangedEvent.OnConfigChangedEvent; package com.github.worldsender.mcanm.client.config; public class MCAnmConfiguration { private Configuration config; private Property enableReload; public MCAnmConfiguration(File loadFile) { config = new Configuration(loadFile); config.load();
enableReload = config.get(Configuration.CATEGORY_GENERAL, Reference.config_reload_enabled, true)
WorldSEnder/MCAnm
src/main/java/com/github/worldsender/mcanm/common/animation/visitor/IAnimationVisitor.java
// Path: src/main/java/com/github/worldsender/mcanm/common/animation/parts/AnimatedTransform.java // public class AnimatedTransform { // public static class AnimatedTransformBuilder { // // private final AnimatedValueBuilder builder = new AnimatedValueBuilder(); // private AnimatedTransform value = null; // // private void checkAvailable() { // value = new AnimatedTransform(); // } // // public AnimatedTransformBuilder fromStream(DataInputStream dis) throws IOException, ModelFormatException { // checkAvailable(); // value.loc_x = builder.setDefaultValue(0.0f).fromStream(dis).buildAndReset(); // value.loc_y = builder.setDefaultValue(0.0f).fromStream(dis).buildAndReset(); // value.loc_z = builder.setDefaultValue(0.0f).fromStream(dis).buildAndReset(); // value.quat_x = builder.setDefaultValue(0.0f).fromStream(dis).buildAndReset(); // value.quat_y = builder.setDefaultValue(0.0f).fromStream(dis).buildAndReset(); // value.quat_z = builder.setDefaultValue(0.0f).fromStream(dis).buildAndReset(); // value.quat_w = builder.setDefaultValue(1.0f).fromStream(dis).buildAndReset(); // value.scale_x = builder.setDefaultValue(1.0f).fromStream(dis).buildAndReset(); // value.scale_y = builder.setDefaultValue(1.0f).fromStream(dis).buildAndReset(); // value.scale_z = builder.setDefaultValue(1.0f).fromStream(dis).buildAndReset(); // return this; // } // // public AnimatedTransform buildAndReset() { // AnimatedTransform ret = value; // return ret; // } // } // // private AnimatedValue loc_x; // private AnimatedValue loc_y; // private AnimatedValue loc_z; // private AnimatedValue quat_x; // private AnimatedValue quat_y; // private AnimatedValue quat_z; // private AnimatedValue quat_w; // private AnimatedValue scale_x; // private AnimatedValue scale_y; // private AnimatedValue scale_z; // // private ThreadLocal<Vector3f> translationBuffer = ThreadLocal.withInitial(Vector3f::new); // private ThreadLocal<Quat4f> rotationBuffer = ThreadLocal.withInitial(Quat4f::new); // private ThreadLocal<Vector3f> scaleBuffer = ThreadLocal.withInitial(Vector3f::new); // // /** // * Reads a {@link AnimatedTransform} from the {@link DataInputStream} given. // * // * @param dis // */ // private AnimatedTransform() { // loc_x = loc_y = loc_z = quat_x = quat_y = quat_z = AnimatedValue.CONSTANT_ZERO; // quat_w = scale_x = scale_y = scale_z = AnimatedValue.CONSTANT_ONE; // } // // /** // * Stores the transformation of the bone at a specific point in the animation. This method interpolates between the // * nearest two key-frames using the correct interpolation mode. // * // * @param frame // * @param transform // * @param subFrame // * @return // */ // public void storeTransformAt(float frame, BoneTransformation transform) { // Vector3f t = translationBuffer.get(); // t.set(loc_x.getValueAt(frame), loc_y.getValueAt(frame), loc_z.getValueAt(frame)); // Quat4f r = rotationBuffer.get(); // r.set(quat_x.getValueAt(frame), quat_y.getValueAt(frame), quat_z.getValueAt(frame), quat_w.getValueAt(frame)); // r.normalize(); // Vector3f s = scaleBuffer.get(); // s.set(scale_x.getValueAt(frame), scale_y.getValueAt(frame), scale_z.getValueAt(frame)); // Utils.fromRTS(r, t, s, transform.matrix); // } // }
import com.github.worldsender.mcanm.common.animation.parts.AnimatedTransform;
package com.github.worldsender.mcanm.common.animation.visitor; public interface IAnimationVisitor { void visitArtist(String artist);
// Path: src/main/java/com/github/worldsender/mcanm/common/animation/parts/AnimatedTransform.java // public class AnimatedTransform { // public static class AnimatedTransformBuilder { // // private final AnimatedValueBuilder builder = new AnimatedValueBuilder(); // private AnimatedTransform value = null; // // private void checkAvailable() { // value = new AnimatedTransform(); // } // // public AnimatedTransformBuilder fromStream(DataInputStream dis) throws IOException, ModelFormatException { // checkAvailable(); // value.loc_x = builder.setDefaultValue(0.0f).fromStream(dis).buildAndReset(); // value.loc_y = builder.setDefaultValue(0.0f).fromStream(dis).buildAndReset(); // value.loc_z = builder.setDefaultValue(0.0f).fromStream(dis).buildAndReset(); // value.quat_x = builder.setDefaultValue(0.0f).fromStream(dis).buildAndReset(); // value.quat_y = builder.setDefaultValue(0.0f).fromStream(dis).buildAndReset(); // value.quat_z = builder.setDefaultValue(0.0f).fromStream(dis).buildAndReset(); // value.quat_w = builder.setDefaultValue(1.0f).fromStream(dis).buildAndReset(); // value.scale_x = builder.setDefaultValue(1.0f).fromStream(dis).buildAndReset(); // value.scale_y = builder.setDefaultValue(1.0f).fromStream(dis).buildAndReset(); // value.scale_z = builder.setDefaultValue(1.0f).fromStream(dis).buildAndReset(); // return this; // } // // public AnimatedTransform buildAndReset() { // AnimatedTransform ret = value; // return ret; // } // } // // private AnimatedValue loc_x; // private AnimatedValue loc_y; // private AnimatedValue loc_z; // private AnimatedValue quat_x; // private AnimatedValue quat_y; // private AnimatedValue quat_z; // private AnimatedValue quat_w; // private AnimatedValue scale_x; // private AnimatedValue scale_y; // private AnimatedValue scale_z; // // private ThreadLocal<Vector3f> translationBuffer = ThreadLocal.withInitial(Vector3f::new); // private ThreadLocal<Quat4f> rotationBuffer = ThreadLocal.withInitial(Quat4f::new); // private ThreadLocal<Vector3f> scaleBuffer = ThreadLocal.withInitial(Vector3f::new); // // /** // * Reads a {@link AnimatedTransform} from the {@link DataInputStream} given. // * // * @param dis // */ // private AnimatedTransform() { // loc_x = loc_y = loc_z = quat_x = quat_y = quat_z = AnimatedValue.CONSTANT_ZERO; // quat_w = scale_x = scale_y = scale_z = AnimatedValue.CONSTANT_ONE; // } // // /** // * Stores the transformation of the bone at a specific point in the animation. This method interpolates between the // * nearest two key-frames using the correct interpolation mode. // * // * @param frame // * @param transform // * @param subFrame // * @return // */ // public void storeTransformAt(float frame, BoneTransformation transform) { // Vector3f t = translationBuffer.get(); // t.set(loc_x.getValueAt(frame), loc_y.getValueAt(frame), loc_z.getValueAt(frame)); // Quat4f r = rotationBuffer.get(); // r.set(quat_x.getValueAt(frame), quat_y.getValueAt(frame), quat_z.getValueAt(frame), quat_w.getValueAt(frame)); // r.normalize(); // Vector3f s = scaleBuffer.get(); // s.set(scale_x.getValueAt(frame), scale_y.getValueAt(frame), scale_z.getValueAt(frame)); // Utils.fromRTS(r, t, s, transform.matrix); // } // } // Path: src/main/java/com/github/worldsender/mcanm/common/animation/visitor/IAnimationVisitor.java import com.github.worldsender.mcanm.common.animation.parts.AnimatedTransform; package com.github.worldsender.mcanm.common.animation.visitor; public interface IAnimationVisitor { void visitArtist(String artist);
void visitBone(String name, AnimatedTransform transform);
WorldSEnder/MCAnm
src/main/java/com/github/worldsender/mcanm/client/mcanmmodel/gl/IModelRenderData.java
// Path: src/main/java/com/github/worldsender/mcanm/client/IRenderPass.java // public interface IRenderPass extends IRenderPassInformation { // /** // * Binds the resource-location given.<br> // * <b>WARNING</b> This does not transform the resourc-location via // * {@link #getActualResourceLocation(ResourceLocation)}. This has the be done before calling this method. // * // * @param resLoc // * the resource to bind // */ // void bindTexture(ResourceLocation resLoc); // } // // Path: src/main/java/com/github/worldsender/mcanm/client/model/IModelStateInformation.java // public interface IModelStateInformation { // // IAnimation getAnimation(); // // float getFrame(); // // boolean shouldRenderPart(String part); // // }
import java.util.List; import java.util.Map; import com.github.worldsender.mcanm.client.IRenderPass; import com.github.worldsender.mcanm.client.model.IModelStateInformation; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.renderer.vertex.VertexFormat;
package com.github.worldsender.mcanm.client.mcanmmodel.gl; /** * Interface for ModelData. * * @author WorldSEnder * */ public interface IModelRenderData { /** * Renders the model from the given RenderPass. * * @param pass */ public void render(IRenderPass pass); /** * The totally inefficient method of minecraft to get block data * * @param currentPass * @param slotToTex * @param format * @return */ List<BakedQuad> getAsBakedQuads(
// Path: src/main/java/com/github/worldsender/mcanm/client/IRenderPass.java // public interface IRenderPass extends IRenderPassInformation { // /** // * Binds the resource-location given.<br> // * <b>WARNING</b> This does not transform the resourc-location via // * {@link #getActualResourceLocation(ResourceLocation)}. This has the be done before calling this method. // * // * @param resLoc // * the resource to bind // */ // void bindTexture(ResourceLocation resLoc); // } // // Path: src/main/java/com/github/worldsender/mcanm/client/model/IModelStateInformation.java // public interface IModelStateInformation { // // IAnimation getAnimation(); // // float getFrame(); // // boolean shouldRenderPart(String part); // // } // Path: src/main/java/com/github/worldsender/mcanm/client/mcanmmodel/gl/IModelRenderData.java import java.util.List; import java.util.Map; import com.github.worldsender.mcanm.client.IRenderPass; import com.github.worldsender.mcanm.client.model.IModelStateInformation; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.renderer.vertex.VertexFormat; package com.github.worldsender.mcanm.client.mcanmmodel.gl; /** * Interface for ModelData. * * @author WorldSEnder * */ public interface IModelRenderData { /** * Renders the model from the given RenderPass. * * @param pass */ public void render(IRenderPass pass); /** * The totally inefficient method of minecraft to get block data * * @param currentPass * @param slotToTex * @param format * @return */ List<BakedQuad> getAsBakedQuads(
IModelStateInformation currentPass,
WorldSEnder/MCAnm
src/main/java/com/github/worldsender/mcanm/common/resource/EmbeddedResourceLocation.java
// Path: src/main/java/com/github/worldsender/mcanm/common/util/CallResolver.java // public class CallResolver extends SecurityManager { // public static final CallResolver INSTANCE = new CallResolver(); // // public Class<?>[] getCallingClasses() { // return getClassContext(); // } // // public Class<?> getCallingClass() { // return getCallingClasses()[3]; // } // }
import java.io.IOException; import java.io.InputStream; import java.net.URL; import com.github.worldsender.mcanm.common.util.CallResolver;
package com.github.worldsender.mcanm.common.resource; public class EmbeddedResourceLocation extends ResourceLocationAdapter { private static InputStream createStream(URL url) throws IOException { if (url == null) { throw new IOException("Couldn't open the stream"); } return url.openStream(); } private /* static */ class EmbeddedResource extends ResourceAdapter { public EmbeddedResource(URL url) throws IOException { super(EmbeddedResourceLocation.this, createStream(url)); } } private final URL url; private final String name; public EmbeddedResourceLocation(String name) {
// Path: src/main/java/com/github/worldsender/mcanm/common/util/CallResolver.java // public class CallResolver extends SecurityManager { // public static final CallResolver INSTANCE = new CallResolver(); // // public Class<?>[] getCallingClasses() { // return getClassContext(); // } // // public Class<?> getCallingClass() { // return getCallingClasses()[3]; // } // } // Path: src/main/java/com/github/worldsender/mcanm/common/resource/EmbeddedResourceLocation.java import java.io.IOException; import java.io.InputStream; import java.net.URL; import com.github.worldsender.mcanm.common.util.CallResolver; package com.github.worldsender.mcanm.common.resource; public class EmbeddedResourceLocation extends ResourceLocationAdapter { private static InputStream createStream(URL url) throws IOException { if (url == null) { throw new IOException("Couldn't open the stream"); } return url.openStream(); } private /* static */ class EmbeddedResource extends ResourceAdapter { public EmbeddedResource(URL url) throws IOException { super(EmbeddedResourceLocation.this, createStream(url)); } } private final URL url; private final String name; public EmbeddedResourceLocation(String name) {
this(name, CallResolver.INSTANCE.getCallingClass().getClassLoader());
WorldSEnder/MCAnm
src/main/java/com/github/worldsender/mcanm/server/ServerProxy.java
// Path: src/main/java/com/github/worldsender/mcanm/Proxy.java // public interface Proxy { // void preInit(); // // void init(); // // /** // * On a client, this will return a {@link MinecraftResourceLocation} that will get reloaded when a new texture pack // * is switched on. On the server, this returns a {@link EmbeddedResourceLocation} using the {@link ClassLoader} of // * the calling class. // * // * @param resLoc // * the resource location to load from. On the server the resource must be packed with the .jar // * @param context // * when the resource is loaded on the server, it is attempted to load it from this class loader // * @return // */ // IResourceLocation getSidedResource(ResourceLocation resLoc, ClassLoader context); // } // // Path: src/main/java/com/github/worldsender/mcanm/common/resource/EmbeddedResourceLocation.java // public class EmbeddedResourceLocation extends ResourceLocationAdapter { // private static InputStream createStream(URL url) throws IOException { // if (url == null) { // throw new IOException("Couldn't open the stream"); // } // return url.openStream(); // } // // private /* static */ class EmbeddedResource extends ResourceAdapter { // public EmbeddedResource(URL url) throws IOException { // super(EmbeddedResourceLocation.this, createStream(url)); // } // } // // private final URL url; // private final String name; // // public EmbeddedResourceLocation(String name) { // this(name, CallResolver.INSTANCE.getCallingClass().getClassLoader()); // } // // public EmbeddedResourceLocation(String name, ClassLoader loader) { // this(loader.getResource(name), name); // } // // public EmbeddedResourceLocation(URL url) { // this(url, null); // } // // public EmbeddedResourceLocation(URL url, String resourceName) { // this.url = url; // this.name = resourceName; // } // // @Override // public IResource open() throws IOException { // return new EmbeddedResource(url); // } // // @Override // public String getResourceName() { // return url != null ? url.toString() : name != null ? name : "<unnamed resource>"; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((url == null) ? 0 : url.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (!(obj instanceof EmbeddedResourceLocation)) { // return false; // } // EmbeddedResourceLocation other = (EmbeddedResourceLocation) obj; // if (url == null) { // if (other.url != null) { // return false; // } // } else if (!url.equals(other.url)) { // return false; // } // return true; // } // } // // Path: src/main/java/com/github/worldsender/mcanm/common/resource/IResourceLocation.java // public interface IResourceLocation { // /** // * For data that has no definite location, this is suitable (e.g. one-time streams) // */ // public static final IResourceLocation UNKNOWN_LOCATION = new IResourceLocation() { // @Override // public IResource open() throws IOException { // throw new NoSuchFileException("Unknown location"); // } // // @Override // public String getResourceName() { // return "<unknown resource>"; // } // // @Override // public boolean shouldCache() { // return false; // } // // @Override // public void registerReloadListener(Consumer<IResourceLocation> reloadListener) { // reloadListener.accept(this); // // Don't store it, this location won't change // } // }; // // /** // * Opens the resource location described by this resource location. // * // * @return an empty optional if the resource is currently (expectedly) absent // * @throws IOException // * if the resource is absent unexpectedly // */ // IResource open() throws IOException; // // /** // * Registers a listener that is being fired every time this resource changes. What "changes" means is deliberately // * left unspecified but a good example would be whenever the {@link Minecraft#getResourceManager()} changes, for // * example when a new resource pack is loaded.<br> // * <b>The initial stick is considered a change already, so this method should also fire the listener once.</b> // * // * @param reloadListener // */ // void registerReloadListener(Consumer<IResourceLocation> reloadListener); // // /** // * A descriptive name of the resource, perhaps the path // * // * @return // */ // String getResourceName(); // // /** // * Returns false if this resource should not be cached, e.g. it is a one-time stream. When a // * {@link IResourceLocation} may get cached, {@link #open()} should succeed multiple times and return the same data // * every time, until the resource is reloaded. // * // * @return // */ // boolean shouldCache(); // // @Override // boolean equals(Object obj); // // @Override // int hashCode(); // }
import com.github.worldsender.mcanm.Proxy; import com.github.worldsender.mcanm.common.resource.EmbeddedResourceLocation; import com.github.worldsender.mcanm.common.resource.IResourceLocation; import net.minecraft.util.ResourceLocation;
package com.github.worldsender.mcanm.server; public class ServerProxy implements Proxy { @Override public void preInit() {} @Override public void init() {} @Override
// Path: src/main/java/com/github/worldsender/mcanm/Proxy.java // public interface Proxy { // void preInit(); // // void init(); // // /** // * On a client, this will return a {@link MinecraftResourceLocation} that will get reloaded when a new texture pack // * is switched on. On the server, this returns a {@link EmbeddedResourceLocation} using the {@link ClassLoader} of // * the calling class. // * // * @param resLoc // * the resource location to load from. On the server the resource must be packed with the .jar // * @param context // * when the resource is loaded on the server, it is attempted to load it from this class loader // * @return // */ // IResourceLocation getSidedResource(ResourceLocation resLoc, ClassLoader context); // } // // Path: src/main/java/com/github/worldsender/mcanm/common/resource/EmbeddedResourceLocation.java // public class EmbeddedResourceLocation extends ResourceLocationAdapter { // private static InputStream createStream(URL url) throws IOException { // if (url == null) { // throw new IOException("Couldn't open the stream"); // } // return url.openStream(); // } // // private /* static */ class EmbeddedResource extends ResourceAdapter { // public EmbeddedResource(URL url) throws IOException { // super(EmbeddedResourceLocation.this, createStream(url)); // } // } // // private final URL url; // private final String name; // // public EmbeddedResourceLocation(String name) { // this(name, CallResolver.INSTANCE.getCallingClass().getClassLoader()); // } // // public EmbeddedResourceLocation(String name, ClassLoader loader) { // this(loader.getResource(name), name); // } // // public EmbeddedResourceLocation(URL url) { // this(url, null); // } // // public EmbeddedResourceLocation(URL url, String resourceName) { // this.url = url; // this.name = resourceName; // } // // @Override // public IResource open() throws IOException { // return new EmbeddedResource(url); // } // // @Override // public String getResourceName() { // return url != null ? url.toString() : name != null ? name : "<unnamed resource>"; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((url == null) ? 0 : url.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (!(obj instanceof EmbeddedResourceLocation)) { // return false; // } // EmbeddedResourceLocation other = (EmbeddedResourceLocation) obj; // if (url == null) { // if (other.url != null) { // return false; // } // } else if (!url.equals(other.url)) { // return false; // } // return true; // } // } // // Path: src/main/java/com/github/worldsender/mcanm/common/resource/IResourceLocation.java // public interface IResourceLocation { // /** // * For data that has no definite location, this is suitable (e.g. one-time streams) // */ // public static final IResourceLocation UNKNOWN_LOCATION = new IResourceLocation() { // @Override // public IResource open() throws IOException { // throw new NoSuchFileException("Unknown location"); // } // // @Override // public String getResourceName() { // return "<unknown resource>"; // } // // @Override // public boolean shouldCache() { // return false; // } // // @Override // public void registerReloadListener(Consumer<IResourceLocation> reloadListener) { // reloadListener.accept(this); // // Don't store it, this location won't change // } // }; // // /** // * Opens the resource location described by this resource location. // * // * @return an empty optional if the resource is currently (expectedly) absent // * @throws IOException // * if the resource is absent unexpectedly // */ // IResource open() throws IOException; // // /** // * Registers a listener that is being fired every time this resource changes. What "changes" means is deliberately // * left unspecified but a good example would be whenever the {@link Minecraft#getResourceManager()} changes, for // * example when a new resource pack is loaded.<br> // * <b>The initial stick is considered a change already, so this method should also fire the listener once.</b> // * // * @param reloadListener // */ // void registerReloadListener(Consumer<IResourceLocation> reloadListener); // // /** // * A descriptive name of the resource, perhaps the path // * // * @return // */ // String getResourceName(); // // /** // * Returns false if this resource should not be cached, e.g. it is a one-time stream. When a // * {@link IResourceLocation} may get cached, {@link #open()} should succeed multiple times and return the same data // * every time, until the resource is reloaded. // * // * @return // */ // boolean shouldCache(); // // @Override // boolean equals(Object obj); // // @Override // int hashCode(); // } // Path: src/main/java/com/github/worldsender/mcanm/server/ServerProxy.java import com.github.worldsender.mcanm.Proxy; import com.github.worldsender.mcanm.common.resource.EmbeddedResourceLocation; import com.github.worldsender.mcanm.common.resource.IResourceLocation; import net.minecraft.util.ResourceLocation; package com.github.worldsender.mcanm.server; public class ServerProxy implements Proxy { @Override public void preInit() {} @Override public void init() {} @Override
public IResourceLocation getSidedResource(ResourceLocation resLoc, ClassLoader context) {
WorldSEnder/MCAnm
src/main/java/com/github/worldsender/mcanm/server/ServerProxy.java
// Path: src/main/java/com/github/worldsender/mcanm/Proxy.java // public interface Proxy { // void preInit(); // // void init(); // // /** // * On a client, this will return a {@link MinecraftResourceLocation} that will get reloaded when a new texture pack // * is switched on. On the server, this returns a {@link EmbeddedResourceLocation} using the {@link ClassLoader} of // * the calling class. // * // * @param resLoc // * the resource location to load from. On the server the resource must be packed with the .jar // * @param context // * when the resource is loaded on the server, it is attempted to load it from this class loader // * @return // */ // IResourceLocation getSidedResource(ResourceLocation resLoc, ClassLoader context); // } // // Path: src/main/java/com/github/worldsender/mcanm/common/resource/EmbeddedResourceLocation.java // public class EmbeddedResourceLocation extends ResourceLocationAdapter { // private static InputStream createStream(URL url) throws IOException { // if (url == null) { // throw new IOException("Couldn't open the stream"); // } // return url.openStream(); // } // // private /* static */ class EmbeddedResource extends ResourceAdapter { // public EmbeddedResource(URL url) throws IOException { // super(EmbeddedResourceLocation.this, createStream(url)); // } // } // // private final URL url; // private final String name; // // public EmbeddedResourceLocation(String name) { // this(name, CallResolver.INSTANCE.getCallingClass().getClassLoader()); // } // // public EmbeddedResourceLocation(String name, ClassLoader loader) { // this(loader.getResource(name), name); // } // // public EmbeddedResourceLocation(URL url) { // this(url, null); // } // // public EmbeddedResourceLocation(URL url, String resourceName) { // this.url = url; // this.name = resourceName; // } // // @Override // public IResource open() throws IOException { // return new EmbeddedResource(url); // } // // @Override // public String getResourceName() { // return url != null ? url.toString() : name != null ? name : "<unnamed resource>"; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((url == null) ? 0 : url.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (!(obj instanceof EmbeddedResourceLocation)) { // return false; // } // EmbeddedResourceLocation other = (EmbeddedResourceLocation) obj; // if (url == null) { // if (other.url != null) { // return false; // } // } else if (!url.equals(other.url)) { // return false; // } // return true; // } // } // // Path: src/main/java/com/github/worldsender/mcanm/common/resource/IResourceLocation.java // public interface IResourceLocation { // /** // * For data that has no definite location, this is suitable (e.g. one-time streams) // */ // public static final IResourceLocation UNKNOWN_LOCATION = new IResourceLocation() { // @Override // public IResource open() throws IOException { // throw new NoSuchFileException("Unknown location"); // } // // @Override // public String getResourceName() { // return "<unknown resource>"; // } // // @Override // public boolean shouldCache() { // return false; // } // // @Override // public void registerReloadListener(Consumer<IResourceLocation> reloadListener) { // reloadListener.accept(this); // // Don't store it, this location won't change // } // }; // // /** // * Opens the resource location described by this resource location. // * // * @return an empty optional if the resource is currently (expectedly) absent // * @throws IOException // * if the resource is absent unexpectedly // */ // IResource open() throws IOException; // // /** // * Registers a listener that is being fired every time this resource changes. What "changes" means is deliberately // * left unspecified but a good example would be whenever the {@link Minecraft#getResourceManager()} changes, for // * example when a new resource pack is loaded.<br> // * <b>The initial stick is considered a change already, so this method should also fire the listener once.</b> // * // * @param reloadListener // */ // void registerReloadListener(Consumer<IResourceLocation> reloadListener); // // /** // * A descriptive name of the resource, perhaps the path // * // * @return // */ // String getResourceName(); // // /** // * Returns false if this resource should not be cached, e.g. it is a one-time stream. When a // * {@link IResourceLocation} may get cached, {@link #open()} should succeed multiple times and return the same data // * every time, until the resource is reloaded. // * // * @return // */ // boolean shouldCache(); // // @Override // boolean equals(Object obj); // // @Override // int hashCode(); // }
import com.github.worldsender.mcanm.Proxy; import com.github.worldsender.mcanm.common.resource.EmbeddedResourceLocation; import com.github.worldsender.mcanm.common.resource.IResourceLocation; import net.minecraft.util.ResourceLocation;
package com.github.worldsender.mcanm.server; public class ServerProxy implements Proxy { @Override public void preInit() {} @Override public void init() {} @Override public IResourceLocation getSidedResource(ResourceLocation resLoc, ClassLoader context) { String path = "assets/" + resLoc.getResourceDomain() + "/" + resLoc.getResourcePath();
// Path: src/main/java/com/github/worldsender/mcanm/Proxy.java // public interface Proxy { // void preInit(); // // void init(); // // /** // * On a client, this will return a {@link MinecraftResourceLocation} that will get reloaded when a new texture pack // * is switched on. On the server, this returns a {@link EmbeddedResourceLocation} using the {@link ClassLoader} of // * the calling class. // * // * @param resLoc // * the resource location to load from. On the server the resource must be packed with the .jar // * @param context // * when the resource is loaded on the server, it is attempted to load it from this class loader // * @return // */ // IResourceLocation getSidedResource(ResourceLocation resLoc, ClassLoader context); // } // // Path: src/main/java/com/github/worldsender/mcanm/common/resource/EmbeddedResourceLocation.java // public class EmbeddedResourceLocation extends ResourceLocationAdapter { // private static InputStream createStream(URL url) throws IOException { // if (url == null) { // throw new IOException("Couldn't open the stream"); // } // return url.openStream(); // } // // private /* static */ class EmbeddedResource extends ResourceAdapter { // public EmbeddedResource(URL url) throws IOException { // super(EmbeddedResourceLocation.this, createStream(url)); // } // } // // private final URL url; // private final String name; // // public EmbeddedResourceLocation(String name) { // this(name, CallResolver.INSTANCE.getCallingClass().getClassLoader()); // } // // public EmbeddedResourceLocation(String name, ClassLoader loader) { // this(loader.getResource(name), name); // } // // public EmbeddedResourceLocation(URL url) { // this(url, null); // } // // public EmbeddedResourceLocation(URL url, String resourceName) { // this.url = url; // this.name = resourceName; // } // // @Override // public IResource open() throws IOException { // return new EmbeddedResource(url); // } // // @Override // public String getResourceName() { // return url != null ? url.toString() : name != null ? name : "<unnamed resource>"; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((url == null) ? 0 : url.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (!(obj instanceof EmbeddedResourceLocation)) { // return false; // } // EmbeddedResourceLocation other = (EmbeddedResourceLocation) obj; // if (url == null) { // if (other.url != null) { // return false; // } // } else if (!url.equals(other.url)) { // return false; // } // return true; // } // } // // Path: src/main/java/com/github/worldsender/mcanm/common/resource/IResourceLocation.java // public interface IResourceLocation { // /** // * For data that has no definite location, this is suitable (e.g. one-time streams) // */ // public static final IResourceLocation UNKNOWN_LOCATION = new IResourceLocation() { // @Override // public IResource open() throws IOException { // throw new NoSuchFileException("Unknown location"); // } // // @Override // public String getResourceName() { // return "<unknown resource>"; // } // // @Override // public boolean shouldCache() { // return false; // } // // @Override // public void registerReloadListener(Consumer<IResourceLocation> reloadListener) { // reloadListener.accept(this); // // Don't store it, this location won't change // } // }; // // /** // * Opens the resource location described by this resource location. // * // * @return an empty optional if the resource is currently (expectedly) absent // * @throws IOException // * if the resource is absent unexpectedly // */ // IResource open() throws IOException; // // /** // * Registers a listener that is being fired every time this resource changes. What "changes" means is deliberately // * left unspecified but a good example would be whenever the {@link Minecraft#getResourceManager()} changes, for // * example when a new resource pack is loaded.<br> // * <b>The initial stick is considered a change already, so this method should also fire the listener once.</b> // * // * @param reloadListener // */ // void registerReloadListener(Consumer<IResourceLocation> reloadListener); // // /** // * A descriptive name of the resource, perhaps the path // * // * @return // */ // String getResourceName(); // // /** // * Returns false if this resource should not be cached, e.g. it is a one-time stream. When a // * {@link IResourceLocation} may get cached, {@link #open()} should succeed multiple times and return the same data // * every time, until the resource is reloaded. // * // * @return // */ // boolean shouldCache(); // // @Override // boolean equals(Object obj); // // @Override // int hashCode(); // } // Path: src/main/java/com/github/worldsender/mcanm/server/ServerProxy.java import com.github.worldsender.mcanm.Proxy; import com.github.worldsender.mcanm.common.resource.EmbeddedResourceLocation; import com.github.worldsender.mcanm.common.resource.IResourceLocation; import net.minecraft.util.ResourceLocation; package com.github.worldsender.mcanm.server; public class ServerProxy implements Proxy { @Override public void preInit() {} @Override public void init() {} @Override public IResourceLocation getSidedResource(ResourceLocation resLoc, ClassLoader context) { String path = "assets/" + resLoc.getResourceDomain() + "/" + resLoc.getResourcePath();
return new EmbeddedResourceLocation(path, context);
WorldSEnder/MCAnm
src/main/java/com/github/worldsender/mcanm/client/mcanmmodel/stored/RawDataV2.java
// Path: src/main/java/com/github/worldsender/mcanm/client/mcanmmodel/stored/parts/Material.java // public class Material { // public String resLocationRaw; // // public static Material readFrom(DataInputStream di) throws IOException { // Material tex = new Material(); // tex.resLocationRaw = Utils.readString(di); // return tex; // } // } // // Path: src/main/java/com/github/worldsender/mcanm/client/mcanmmodel/stored/parts/ModelPartV2.java // public class ModelPartV2 { // public String name; // /** All available {@link TesselationPoint}s in this part of the model */ // public TesselationPoint[] points; // /** // * The array to store the order of the {@link TesselationPoint}s. To be interpreted as unsigned. // */ // public short[] indices; // /** The materialIndex index part of the model uses (unsigned byte) */ // public int materialIndex; // // public static ModelPartV2 readFrom(DataInputStream dis) throws IOException { // ModelPartV2 data = new ModelPartV2(); // int nbrPoints = dis.readUnsignedShort(); // int nbrIndices = dis.readUnsignedShort() * 3; // data.points = new TesselationPoint[nbrPoints]; // data.indices = new short[nbrIndices]; // data.name = Utils.readString(dis); // data.materialIndex = dis.readUnsignedByte(); // for (int i = 0; i < nbrPoints; i++) { // data.points[i] = TesselationPoint.readFrom(dis); // } // for (int i = 0; i < nbrIndices; i++) { // data.indices[i] = dis.readShort(); // } // return data; // } // } // // Path: src/main/java/com/github/worldsender/mcanm/client/mcanmmodel/visitor/IMaterialVisitor.java // public interface IMaterialVisitor { // void visitTexture(String textureName); // // void visitEnd(); // } // // Path: src/main/java/com/github/worldsender/mcanm/client/mcanmmodel/visitor/IModelVisitor.java // public interface IModelVisitor { // void visitModelUUID(UUID uuid); // // void visitArtist(String artist); // // IPartVisitor visitPart(String name); // // void visitEnd(); // } // // Path: src/main/java/com/github/worldsender/mcanm/client/mcanmmodel/visitor/IPartVisitor.java // public interface IPartVisitor { // void visitTesselationPoint(TesselationPoint point); // // default void visitTesselationPoints(Iterable<TesselationPoint> points) { // for (TesselationPoint p : points) { // visitTesselationPoint(p); // } // } // // default void visitTesselationPoints(TesselationPoint[] points) { // this.visitTesselationPoints(Arrays.asList(points)); // } // // /** // * Visit a face. Parameters are zero-based indices in the order of visitation of the tesselation points. Tesselation // * points might be visited before or afterwards. // * // * @param tess1 // * @param tess2 // * @param tess3 // */ // void visitFace(short tess1, short tess2, short tess3); // // /** // * Visit multiple faces at once. // * // * @param tessOrder // * short[]#length must be divisible by 3 // * @see #visitFace(short, short, short) // */ // default void visitFaces(short[] tessOrder) { // if (tessOrder.length % 3 != 0) { // throw new IllegalArgumentException(); // } // int maxI = tessOrder.length / 3; // for (int i = 0; i < maxI; i++) { // visitFace(tessOrder[i], tessOrder[i + 1], tessOrder[i + 2]); // } // } // // IMaterialVisitor visitTexture(); // // void visitEnd(); // } // // Path: src/main/java/com/github/worldsender/mcanm/common/exceptions/ModelFormatException.java // public class ModelFormatException extends IllegalArgumentException { // /** // * // */ // private static final long serialVersionUID = -4000239134878464297L; // // public ModelFormatException() { // super(); // } // // public ModelFormatException(String message) { // super(message); // } // // public ModelFormatException(Throwable cause) { // super(cause); // } // // public ModelFormatException(String message, Throwable cause) { // super(message, cause); // } // }
import java.io.DataInputStream; import java.io.IOException; import com.github.worldsender.mcanm.client.mcanmmodel.stored.parts.Material; import com.github.worldsender.mcanm.client.mcanmmodel.stored.parts.ModelPartV2; import com.github.worldsender.mcanm.client.mcanmmodel.visitor.IMaterialVisitor; import com.github.worldsender.mcanm.client.mcanmmodel.visitor.IModelVisitor; import com.github.worldsender.mcanm.client.mcanmmodel.visitor.IPartVisitor; import com.github.worldsender.mcanm.common.exceptions.ModelFormatException;
package com.github.worldsender.mcanm.client.mcanmmodel.stored; public class RawDataV2 implements IVersionSpecificData { private ModelPartV2[] parts;
// Path: src/main/java/com/github/worldsender/mcanm/client/mcanmmodel/stored/parts/Material.java // public class Material { // public String resLocationRaw; // // public static Material readFrom(DataInputStream di) throws IOException { // Material tex = new Material(); // tex.resLocationRaw = Utils.readString(di); // return tex; // } // } // // Path: src/main/java/com/github/worldsender/mcanm/client/mcanmmodel/stored/parts/ModelPartV2.java // public class ModelPartV2 { // public String name; // /** All available {@link TesselationPoint}s in this part of the model */ // public TesselationPoint[] points; // /** // * The array to store the order of the {@link TesselationPoint}s. To be interpreted as unsigned. // */ // public short[] indices; // /** The materialIndex index part of the model uses (unsigned byte) */ // public int materialIndex; // // public static ModelPartV2 readFrom(DataInputStream dis) throws IOException { // ModelPartV2 data = new ModelPartV2(); // int nbrPoints = dis.readUnsignedShort(); // int nbrIndices = dis.readUnsignedShort() * 3; // data.points = new TesselationPoint[nbrPoints]; // data.indices = new short[nbrIndices]; // data.name = Utils.readString(dis); // data.materialIndex = dis.readUnsignedByte(); // for (int i = 0; i < nbrPoints; i++) { // data.points[i] = TesselationPoint.readFrom(dis); // } // for (int i = 0; i < nbrIndices; i++) { // data.indices[i] = dis.readShort(); // } // return data; // } // } // // Path: src/main/java/com/github/worldsender/mcanm/client/mcanmmodel/visitor/IMaterialVisitor.java // public interface IMaterialVisitor { // void visitTexture(String textureName); // // void visitEnd(); // } // // Path: src/main/java/com/github/worldsender/mcanm/client/mcanmmodel/visitor/IModelVisitor.java // public interface IModelVisitor { // void visitModelUUID(UUID uuid); // // void visitArtist(String artist); // // IPartVisitor visitPart(String name); // // void visitEnd(); // } // // Path: src/main/java/com/github/worldsender/mcanm/client/mcanmmodel/visitor/IPartVisitor.java // public interface IPartVisitor { // void visitTesselationPoint(TesselationPoint point); // // default void visitTesselationPoints(Iterable<TesselationPoint> points) { // for (TesselationPoint p : points) { // visitTesselationPoint(p); // } // } // // default void visitTesselationPoints(TesselationPoint[] points) { // this.visitTesselationPoints(Arrays.asList(points)); // } // // /** // * Visit a face. Parameters are zero-based indices in the order of visitation of the tesselation points. Tesselation // * points might be visited before or afterwards. // * // * @param tess1 // * @param tess2 // * @param tess3 // */ // void visitFace(short tess1, short tess2, short tess3); // // /** // * Visit multiple faces at once. // * // * @param tessOrder // * short[]#length must be divisible by 3 // * @see #visitFace(short, short, short) // */ // default void visitFaces(short[] tessOrder) { // if (tessOrder.length % 3 != 0) { // throw new IllegalArgumentException(); // } // int maxI = tessOrder.length / 3; // for (int i = 0; i < maxI; i++) { // visitFace(tessOrder[i], tessOrder[i + 1], tessOrder[i + 2]); // } // } // // IMaterialVisitor visitTexture(); // // void visitEnd(); // } // // Path: src/main/java/com/github/worldsender/mcanm/common/exceptions/ModelFormatException.java // public class ModelFormatException extends IllegalArgumentException { // /** // * // */ // private static final long serialVersionUID = -4000239134878464297L; // // public ModelFormatException() { // super(); // } // // public ModelFormatException(String message) { // super(message); // } // // public ModelFormatException(Throwable cause) { // super(cause); // } // // public ModelFormatException(String message, Throwable cause) { // super(message, cause); // } // } // Path: src/main/java/com/github/worldsender/mcanm/client/mcanmmodel/stored/RawDataV2.java import java.io.DataInputStream; import java.io.IOException; import com.github.worldsender.mcanm.client.mcanmmodel.stored.parts.Material; import com.github.worldsender.mcanm.client.mcanmmodel.stored.parts.ModelPartV2; import com.github.worldsender.mcanm.client.mcanmmodel.visitor.IMaterialVisitor; import com.github.worldsender.mcanm.client.mcanmmodel.visitor.IModelVisitor; import com.github.worldsender.mcanm.client.mcanmmodel.visitor.IPartVisitor; import com.github.worldsender.mcanm.common.exceptions.ModelFormatException; package com.github.worldsender.mcanm.client.mcanmmodel.stored; public class RawDataV2 implements IVersionSpecificData { private ModelPartV2[] parts;
private Material[] mats;
WorldSEnder/MCAnm
src/main/java/com/github/worldsender/mcanm/client/mcanmmodel/stored/RawDataV2.java
// Path: src/main/java/com/github/worldsender/mcanm/client/mcanmmodel/stored/parts/Material.java // public class Material { // public String resLocationRaw; // // public static Material readFrom(DataInputStream di) throws IOException { // Material tex = new Material(); // tex.resLocationRaw = Utils.readString(di); // return tex; // } // } // // Path: src/main/java/com/github/worldsender/mcanm/client/mcanmmodel/stored/parts/ModelPartV2.java // public class ModelPartV2 { // public String name; // /** All available {@link TesselationPoint}s in this part of the model */ // public TesselationPoint[] points; // /** // * The array to store the order of the {@link TesselationPoint}s. To be interpreted as unsigned. // */ // public short[] indices; // /** The materialIndex index part of the model uses (unsigned byte) */ // public int materialIndex; // // public static ModelPartV2 readFrom(DataInputStream dis) throws IOException { // ModelPartV2 data = new ModelPartV2(); // int nbrPoints = dis.readUnsignedShort(); // int nbrIndices = dis.readUnsignedShort() * 3; // data.points = new TesselationPoint[nbrPoints]; // data.indices = new short[nbrIndices]; // data.name = Utils.readString(dis); // data.materialIndex = dis.readUnsignedByte(); // for (int i = 0; i < nbrPoints; i++) { // data.points[i] = TesselationPoint.readFrom(dis); // } // for (int i = 0; i < nbrIndices; i++) { // data.indices[i] = dis.readShort(); // } // return data; // } // } // // Path: src/main/java/com/github/worldsender/mcanm/client/mcanmmodel/visitor/IMaterialVisitor.java // public interface IMaterialVisitor { // void visitTexture(String textureName); // // void visitEnd(); // } // // Path: src/main/java/com/github/worldsender/mcanm/client/mcanmmodel/visitor/IModelVisitor.java // public interface IModelVisitor { // void visitModelUUID(UUID uuid); // // void visitArtist(String artist); // // IPartVisitor visitPart(String name); // // void visitEnd(); // } // // Path: src/main/java/com/github/worldsender/mcanm/client/mcanmmodel/visitor/IPartVisitor.java // public interface IPartVisitor { // void visitTesselationPoint(TesselationPoint point); // // default void visitTesselationPoints(Iterable<TesselationPoint> points) { // for (TesselationPoint p : points) { // visitTesselationPoint(p); // } // } // // default void visitTesselationPoints(TesselationPoint[] points) { // this.visitTesselationPoints(Arrays.asList(points)); // } // // /** // * Visit a face. Parameters are zero-based indices in the order of visitation of the tesselation points. Tesselation // * points might be visited before or afterwards. // * // * @param tess1 // * @param tess2 // * @param tess3 // */ // void visitFace(short tess1, short tess2, short tess3); // // /** // * Visit multiple faces at once. // * // * @param tessOrder // * short[]#length must be divisible by 3 // * @see #visitFace(short, short, short) // */ // default void visitFaces(short[] tessOrder) { // if (tessOrder.length % 3 != 0) { // throw new IllegalArgumentException(); // } // int maxI = tessOrder.length / 3; // for (int i = 0; i < maxI; i++) { // visitFace(tessOrder[i], tessOrder[i + 1], tessOrder[i + 2]); // } // } // // IMaterialVisitor visitTexture(); // // void visitEnd(); // } // // Path: src/main/java/com/github/worldsender/mcanm/common/exceptions/ModelFormatException.java // public class ModelFormatException extends IllegalArgumentException { // /** // * // */ // private static final long serialVersionUID = -4000239134878464297L; // // public ModelFormatException() { // super(); // } // // public ModelFormatException(String message) { // super(message); // } // // public ModelFormatException(Throwable cause) { // super(cause); // } // // public ModelFormatException(String message, Throwable cause) { // super(message, cause); // } // }
import java.io.DataInputStream; import java.io.IOException; import com.github.worldsender.mcanm.client.mcanmmodel.stored.parts.Material; import com.github.worldsender.mcanm.client.mcanmmodel.stored.parts.ModelPartV2; import com.github.worldsender.mcanm.client.mcanmmodel.visitor.IMaterialVisitor; import com.github.worldsender.mcanm.client.mcanmmodel.visitor.IModelVisitor; import com.github.worldsender.mcanm.client.mcanmmodel.visitor.IPartVisitor; import com.github.worldsender.mcanm.common.exceptions.ModelFormatException;
package com.github.worldsender.mcanm.client.mcanmmodel.stored; public class RawDataV2 implements IVersionSpecificData { private ModelPartV2[] parts; private Material[] mats; @Override
// Path: src/main/java/com/github/worldsender/mcanm/client/mcanmmodel/stored/parts/Material.java // public class Material { // public String resLocationRaw; // // public static Material readFrom(DataInputStream di) throws IOException { // Material tex = new Material(); // tex.resLocationRaw = Utils.readString(di); // return tex; // } // } // // Path: src/main/java/com/github/worldsender/mcanm/client/mcanmmodel/stored/parts/ModelPartV2.java // public class ModelPartV2 { // public String name; // /** All available {@link TesselationPoint}s in this part of the model */ // public TesselationPoint[] points; // /** // * The array to store the order of the {@link TesselationPoint}s. To be interpreted as unsigned. // */ // public short[] indices; // /** The materialIndex index part of the model uses (unsigned byte) */ // public int materialIndex; // // public static ModelPartV2 readFrom(DataInputStream dis) throws IOException { // ModelPartV2 data = new ModelPartV2(); // int nbrPoints = dis.readUnsignedShort(); // int nbrIndices = dis.readUnsignedShort() * 3; // data.points = new TesselationPoint[nbrPoints]; // data.indices = new short[nbrIndices]; // data.name = Utils.readString(dis); // data.materialIndex = dis.readUnsignedByte(); // for (int i = 0; i < nbrPoints; i++) { // data.points[i] = TesselationPoint.readFrom(dis); // } // for (int i = 0; i < nbrIndices; i++) { // data.indices[i] = dis.readShort(); // } // return data; // } // } // // Path: src/main/java/com/github/worldsender/mcanm/client/mcanmmodel/visitor/IMaterialVisitor.java // public interface IMaterialVisitor { // void visitTexture(String textureName); // // void visitEnd(); // } // // Path: src/main/java/com/github/worldsender/mcanm/client/mcanmmodel/visitor/IModelVisitor.java // public interface IModelVisitor { // void visitModelUUID(UUID uuid); // // void visitArtist(String artist); // // IPartVisitor visitPart(String name); // // void visitEnd(); // } // // Path: src/main/java/com/github/worldsender/mcanm/client/mcanmmodel/visitor/IPartVisitor.java // public interface IPartVisitor { // void visitTesselationPoint(TesselationPoint point); // // default void visitTesselationPoints(Iterable<TesselationPoint> points) { // for (TesselationPoint p : points) { // visitTesselationPoint(p); // } // } // // default void visitTesselationPoints(TesselationPoint[] points) { // this.visitTesselationPoints(Arrays.asList(points)); // } // // /** // * Visit a face. Parameters are zero-based indices in the order of visitation of the tesselation points. Tesselation // * points might be visited before or afterwards. // * // * @param tess1 // * @param tess2 // * @param tess3 // */ // void visitFace(short tess1, short tess2, short tess3); // // /** // * Visit multiple faces at once. // * // * @param tessOrder // * short[]#length must be divisible by 3 // * @see #visitFace(short, short, short) // */ // default void visitFaces(short[] tessOrder) { // if (tessOrder.length % 3 != 0) { // throw new IllegalArgumentException(); // } // int maxI = tessOrder.length / 3; // for (int i = 0; i < maxI; i++) { // visitFace(tessOrder[i], tessOrder[i + 1], tessOrder[i + 2]); // } // } // // IMaterialVisitor visitTexture(); // // void visitEnd(); // } // // Path: src/main/java/com/github/worldsender/mcanm/common/exceptions/ModelFormatException.java // public class ModelFormatException extends IllegalArgumentException { // /** // * // */ // private static final long serialVersionUID = -4000239134878464297L; // // public ModelFormatException() { // super(); // } // // public ModelFormatException(String message) { // super(message); // } // // public ModelFormatException(Throwable cause) { // super(cause); // } // // public ModelFormatException(String message, Throwable cause) { // super(message, cause); // } // } // Path: src/main/java/com/github/worldsender/mcanm/client/mcanmmodel/stored/RawDataV2.java import java.io.DataInputStream; import java.io.IOException; import com.github.worldsender.mcanm.client.mcanmmodel.stored.parts.Material; import com.github.worldsender.mcanm.client.mcanmmodel.stored.parts.ModelPartV2; import com.github.worldsender.mcanm.client.mcanmmodel.visitor.IMaterialVisitor; import com.github.worldsender.mcanm.client.mcanmmodel.visitor.IModelVisitor; import com.github.worldsender.mcanm.client.mcanmmodel.visitor.IPartVisitor; import com.github.worldsender.mcanm.common.exceptions.ModelFormatException; package com.github.worldsender.mcanm.client.mcanmmodel.stored; public class RawDataV2 implements IVersionSpecificData { private ModelPartV2[] parts; private Material[] mats; @Override
public void visitBy(IModelVisitor visitor) {
WorldSEnder/MCAnm
src/main/java/com/github/worldsender/mcanm/client/mcanmmodel/stored/RawDataV2.java
// Path: src/main/java/com/github/worldsender/mcanm/client/mcanmmodel/stored/parts/Material.java // public class Material { // public String resLocationRaw; // // public static Material readFrom(DataInputStream di) throws IOException { // Material tex = new Material(); // tex.resLocationRaw = Utils.readString(di); // return tex; // } // } // // Path: src/main/java/com/github/worldsender/mcanm/client/mcanmmodel/stored/parts/ModelPartV2.java // public class ModelPartV2 { // public String name; // /** All available {@link TesselationPoint}s in this part of the model */ // public TesselationPoint[] points; // /** // * The array to store the order of the {@link TesselationPoint}s. To be interpreted as unsigned. // */ // public short[] indices; // /** The materialIndex index part of the model uses (unsigned byte) */ // public int materialIndex; // // public static ModelPartV2 readFrom(DataInputStream dis) throws IOException { // ModelPartV2 data = new ModelPartV2(); // int nbrPoints = dis.readUnsignedShort(); // int nbrIndices = dis.readUnsignedShort() * 3; // data.points = new TesselationPoint[nbrPoints]; // data.indices = new short[nbrIndices]; // data.name = Utils.readString(dis); // data.materialIndex = dis.readUnsignedByte(); // for (int i = 0; i < nbrPoints; i++) { // data.points[i] = TesselationPoint.readFrom(dis); // } // for (int i = 0; i < nbrIndices; i++) { // data.indices[i] = dis.readShort(); // } // return data; // } // } // // Path: src/main/java/com/github/worldsender/mcanm/client/mcanmmodel/visitor/IMaterialVisitor.java // public interface IMaterialVisitor { // void visitTexture(String textureName); // // void visitEnd(); // } // // Path: src/main/java/com/github/worldsender/mcanm/client/mcanmmodel/visitor/IModelVisitor.java // public interface IModelVisitor { // void visitModelUUID(UUID uuid); // // void visitArtist(String artist); // // IPartVisitor visitPart(String name); // // void visitEnd(); // } // // Path: src/main/java/com/github/worldsender/mcanm/client/mcanmmodel/visitor/IPartVisitor.java // public interface IPartVisitor { // void visitTesselationPoint(TesselationPoint point); // // default void visitTesselationPoints(Iterable<TesselationPoint> points) { // for (TesselationPoint p : points) { // visitTesselationPoint(p); // } // } // // default void visitTesselationPoints(TesselationPoint[] points) { // this.visitTesselationPoints(Arrays.asList(points)); // } // // /** // * Visit a face. Parameters are zero-based indices in the order of visitation of the tesselation points. Tesselation // * points might be visited before or afterwards. // * // * @param tess1 // * @param tess2 // * @param tess3 // */ // void visitFace(short tess1, short tess2, short tess3); // // /** // * Visit multiple faces at once. // * // * @param tessOrder // * short[]#length must be divisible by 3 // * @see #visitFace(short, short, short) // */ // default void visitFaces(short[] tessOrder) { // if (tessOrder.length % 3 != 0) { // throw new IllegalArgumentException(); // } // int maxI = tessOrder.length / 3; // for (int i = 0; i < maxI; i++) { // visitFace(tessOrder[i], tessOrder[i + 1], tessOrder[i + 2]); // } // } // // IMaterialVisitor visitTexture(); // // void visitEnd(); // } // // Path: src/main/java/com/github/worldsender/mcanm/common/exceptions/ModelFormatException.java // public class ModelFormatException extends IllegalArgumentException { // /** // * // */ // private static final long serialVersionUID = -4000239134878464297L; // // public ModelFormatException() { // super(); // } // // public ModelFormatException(String message) { // super(message); // } // // public ModelFormatException(Throwable cause) { // super(cause); // } // // public ModelFormatException(String message, Throwable cause) { // super(message, cause); // } // }
import java.io.DataInputStream; import java.io.IOException; import com.github.worldsender.mcanm.client.mcanmmodel.stored.parts.Material; import com.github.worldsender.mcanm.client.mcanmmodel.stored.parts.ModelPartV2; import com.github.worldsender.mcanm.client.mcanmmodel.visitor.IMaterialVisitor; import com.github.worldsender.mcanm.client.mcanmmodel.visitor.IModelVisitor; import com.github.worldsender.mcanm.client.mcanmmodel.visitor.IPartVisitor; import com.github.worldsender.mcanm.common.exceptions.ModelFormatException;
package com.github.worldsender.mcanm.client.mcanmmodel.stored; public class RawDataV2 implements IVersionSpecificData { private ModelPartV2[] parts; private Material[] mats; @Override public void visitBy(IModelVisitor visitor) { for (ModelPartV2 part : parts) {
// Path: src/main/java/com/github/worldsender/mcanm/client/mcanmmodel/stored/parts/Material.java // public class Material { // public String resLocationRaw; // // public static Material readFrom(DataInputStream di) throws IOException { // Material tex = new Material(); // tex.resLocationRaw = Utils.readString(di); // return tex; // } // } // // Path: src/main/java/com/github/worldsender/mcanm/client/mcanmmodel/stored/parts/ModelPartV2.java // public class ModelPartV2 { // public String name; // /** All available {@link TesselationPoint}s in this part of the model */ // public TesselationPoint[] points; // /** // * The array to store the order of the {@link TesselationPoint}s. To be interpreted as unsigned. // */ // public short[] indices; // /** The materialIndex index part of the model uses (unsigned byte) */ // public int materialIndex; // // public static ModelPartV2 readFrom(DataInputStream dis) throws IOException { // ModelPartV2 data = new ModelPartV2(); // int nbrPoints = dis.readUnsignedShort(); // int nbrIndices = dis.readUnsignedShort() * 3; // data.points = new TesselationPoint[nbrPoints]; // data.indices = new short[nbrIndices]; // data.name = Utils.readString(dis); // data.materialIndex = dis.readUnsignedByte(); // for (int i = 0; i < nbrPoints; i++) { // data.points[i] = TesselationPoint.readFrom(dis); // } // for (int i = 0; i < nbrIndices; i++) { // data.indices[i] = dis.readShort(); // } // return data; // } // } // // Path: src/main/java/com/github/worldsender/mcanm/client/mcanmmodel/visitor/IMaterialVisitor.java // public interface IMaterialVisitor { // void visitTexture(String textureName); // // void visitEnd(); // } // // Path: src/main/java/com/github/worldsender/mcanm/client/mcanmmodel/visitor/IModelVisitor.java // public interface IModelVisitor { // void visitModelUUID(UUID uuid); // // void visitArtist(String artist); // // IPartVisitor visitPart(String name); // // void visitEnd(); // } // // Path: src/main/java/com/github/worldsender/mcanm/client/mcanmmodel/visitor/IPartVisitor.java // public interface IPartVisitor { // void visitTesselationPoint(TesselationPoint point); // // default void visitTesselationPoints(Iterable<TesselationPoint> points) { // for (TesselationPoint p : points) { // visitTesselationPoint(p); // } // } // // default void visitTesselationPoints(TesselationPoint[] points) { // this.visitTesselationPoints(Arrays.asList(points)); // } // // /** // * Visit a face. Parameters are zero-based indices in the order of visitation of the tesselation points. Tesselation // * points might be visited before or afterwards. // * // * @param tess1 // * @param tess2 // * @param tess3 // */ // void visitFace(short tess1, short tess2, short tess3); // // /** // * Visit multiple faces at once. // * // * @param tessOrder // * short[]#length must be divisible by 3 // * @see #visitFace(short, short, short) // */ // default void visitFaces(short[] tessOrder) { // if (tessOrder.length % 3 != 0) { // throw new IllegalArgumentException(); // } // int maxI = tessOrder.length / 3; // for (int i = 0; i < maxI; i++) { // visitFace(tessOrder[i], tessOrder[i + 1], tessOrder[i + 2]); // } // } // // IMaterialVisitor visitTexture(); // // void visitEnd(); // } // // Path: src/main/java/com/github/worldsender/mcanm/common/exceptions/ModelFormatException.java // public class ModelFormatException extends IllegalArgumentException { // /** // * // */ // private static final long serialVersionUID = -4000239134878464297L; // // public ModelFormatException() { // super(); // } // // public ModelFormatException(String message) { // super(message); // } // // public ModelFormatException(Throwable cause) { // super(cause); // } // // public ModelFormatException(String message, Throwable cause) { // super(message, cause); // } // } // Path: src/main/java/com/github/worldsender/mcanm/client/mcanmmodel/stored/RawDataV2.java import java.io.DataInputStream; import java.io.IOException; import com.github.worldsender.mcanm.client.mcanmmodel.stored.parts.Material; import com.github.worldsender.mcanm.client.mcanmmodel.stored.parts.ModelPartV2; import com.github.worldsender.mcanm.client.mcanmmodel.visitor.IMaterialVisitor; import com.github.worldsender.mcanm.client.mcanmmodel.visitor.IModelVisitor; import com.github.worldsender.mcanm.client.mcanmmodel.visitor.IPartVisitor; import com.github.worldsender.mcanm.common.exceptions.ModelFormatException; package com.github.worldsender.mcanm.client.mcanmmodel.stored; public class RawDataV2 implements IVersionSpecificData { private ModelPartV2[] parts; private Material[] mats; @Override public void visitBy(IModelVisitor visitor) { for (ModelPartV2 part : parts) {
IPartVisitor partVisitor = visitor.visitPart(part.name);
WorldSEnder/MCAnm
src/main/java/com/github/worldsender/mcanm/client/mcanmmodel/stored/RawDataV2.java
// Path: src/main/java/com/github/worldsender/mcanm/client/mcanmmodel/stored/parts/Material.java // public class Material { // public String resLocationRaw; // // public static Material readFrom(DataInputStream di) throws IOException { // Material tex = new Material(); // tex.resLocationRaw = Utils.readString(di); // return tex; // } // } // // Path: src/main/java/com/github/worldsender/mcanm/client/mcanmmodel/stored/parts/ModelPartV2.java // public class ModelPartV2 { // public String name; // /** All available {@link TesselationPoint}s in this part of the model */ // public TesselationPoint[] points; // /** // * The array to store the order of the {@link TesselationPoint}s. To be interpreted as unsigned. // */ // public short[] indices; // /** The materialIndex index part of the model uses (unsigned byte) */ // public int materialIndex; // // public static ModelPartV2 readFrom(DataInputStream dis) throws IOException { // ModelPartV2 data = new ModelPartV2(); // int nbrPoints = dis.readUnsignedShort(); // int nbrIndices = dis.readUnsignedShort() * 3; // data.points = new TesselationPoint[nbrPoints]; // data.indices = new short[nbrIndices]; // data.name = Utils.readString(dis); // data.materialIndex = dis.readUnsignedByte(); // for (int i = 0; i < nbrPoints; i++) { // data.points[i] = TesselationPoint.readFrom(dis); // } // for (int i = 0; i < nbrIndices; i++) { // data.indices[i] = dis.readShort(); // } // return data; // } // } // // Path: src/main/java/com/github/worldsender/mcanm/client/mcanmmodel/visitor/IMaterialVisitor.java // public interface IMaterialVisitor { // void visitTexture(String textureName); // // void visitEnd(); // } // // Path: src/main/java/com/github/worldsender/mcanm/client/mcanmmodel/visitor/IModelVisitor.java // public interface IModelVisitor { // void visitModelUUID(UUID uuid); // // void visitArtist(String artist); // // IPartVisitor visitPart(String name); // // void visitEnd(); // } // // Path: src/main/java/com/github/worldsender/mcanm/client/mcanmmodel/visitor/IPartVisitor.java // public interface IPartVisitor { // void visitTesselationPoint(TesselationPoint point); // // default void visitTesselationPoints(Iterable<TesselationPoint> points) { // for (TesselationPoint p : points) { // visitTesselationPoint(p); // } // } // // default void visitTesselationPoints(TesselationPoint[] points) { // this.visitTesselationPoints(Arrays.asList(points)); // } // // /** // * Visit a face. Parameters are zero-based indices in the order of visitation of the tesselation points. Tesselation // * points might be visited before or afterwards. // * // * @param tess1 // * @param tess2 // * @param tess3 // */ // void visitFace(short tess1, short tess2, short tess3); // // /** // * Visit multiple faces at once. // * // * @param tessOrder // * short[]#length must be divisible by 3 // * @see #visitFace(short, short, short) // */ // default void visitFaces(short[] tessOrder) { // if (tessOrder.length % 3 != 0) { // throw new IllegalArgumentException(); // } // int maxI = tessOrder.length / 3; // for (int i = 0; i < maxI; i++) { // visitFace(tessOrder[i], tessOrder[i + 1], tessOrder[i + 2]); // } // } // // IMaterialVisitor visitTexture(); // // void visitEnd(); // } // // Path: src/main/java/com/github/worldsender/mcanm/common/exceptions/ModelFormatException.java // public class ModelFormatException extends IllegalArgumentException { // /** // * // */ // private static final long serialVersionUID = -4000239134878464297L; // // public ModelFormatException() { // super(); // } // // public ModelFormatException(String message) { // super(message); // } // // public ModelFormatException(Throwable cause) { // super(cause); // } // // public ModelFormatException(String message, Throwable cause) { // super(message, cause); // } // }
import java.io.DataInputStream; import java.io.IOException; import com.github.worldsender.mcanm.client.mcanmmodel.stored.parts.Material; import com.github.worldsender.mcanm.client.mcanmmodel.stored.parts.ModelPartV2; import com.github.worldsender.mcanm.client.mcanmmodel.visitor.IMaterialVisitor; import com.github.worldsender.mcanm.client.mcanmmodel.visitor.IModelVisitor; import com.github.worldsender.mcanm.client.mcanmmodel.visitor.IPartVisitor; import com.github.worldsender.mcanm.common.exceptions.ModelFormatException;
package com.github.worldsender.mcanm.client.mcanmmodel.stored; public class RawDataV2 implements IVersionSpecificData { private ModelPartV2[] parts; private Material[] mats; @Override public void visitBy(IModelVisitor visitor) { for (ModelPartV2 part : parts) { IPartVisitor partVisitor = visitor.visitPart(part.name); partVisitor.visitTesselationPoints(part.points); partVisitor.visitFaces(part.indices); {
// Path: src/main/java/com/github/worldsender/mcanm/client/mcanmmodel/stored/parts/Material.java // public class Material { // public String resLocationRaw; // // public static Material readFrom(DataInputStream di) throws IOException { // Material tex = new Material(); // tex.resLocationRaw = Utils.readString(di); // return tex; // } // } // // Path: src/main/java/com/github/worldsender/mcanm/client/mcanmmodel/stored/parts/ModelPartV2.java // public class ModelPartV2 { // public String name; // /** All available {@link TesselationPoint}s in this part of the model */ // public TesselationPoint[] points; // /** // * The array to store the order of the {@link TesselationPoint}s. To be interpreted as unsigned. // */ // public short[] indices; // /** The materialIndex index part of the model uses (unsigned byte) */ // public int materialIndex; // // public static ModelPartV2 readFrom(DataInputStream dis) throws IOException { // ModelPartV2 data = new ModelPartV2(); // int nbrPoints = dis.readUnsignedShort(); // int nbrIndices = dis.readUnsignedShort() * 3; // data.points = new TesselationPoint[nbrPoints]; // data.indices = new short[nbrIndices]; // data.name = Utils.readString(dis); // data.materialIndex = dis.readUnsignedByte(); // for (int i = 0; i < nbrPoints; i++) { // data.points[i] = TesselationPoint.readFrom(dis); // } // for (int i = 0; i < nbrIndices; i++) { // data.indices[i] = dis.readShort(); // } // return data; // } // } // // Path: src/main/java/com/github/worldsender/mcanm/client/mcanmmodel/visitor/IMaterialVisitor.java // public interface IMaterialVisitor { // void visitTexture(String textureName); // // void visitEnd(); // } // // Path: src/main/java/com/github/worldsender/mcanm/client/mcanmmodel/visitor/IModelVisitor.java // public interface IModelVisitor { // void visitModelUUID(UUID uuid); // // void visitArtist(String artist); // // IPartVisitor visitPart(String name); // // void visitEnd(); // } // // Path: src/main/java/com/github/worldsender/mcanm/client/mcanmmodel/visitor/IPartVisitor.java // public interface IPartVisitor { // void visitTesselationPoint(TesselationPoint point); // // default void visitTesselationPoints(Iterable<TesselationPoint> points) { // for (TesselationPoint p : points) { // visitTesselationPoint(p); // } // } // // default void visitTesselationPoints(TesselationPoint[] points) { // this.visitTesselationPoints(Arrays.asList(points)); // } // // /** // * Visit a face. Parameters are zero-based indices in the order of visitation of the tesselation points. Tesselation // * points might be visited before or afterwards. // * // * @param tess1 // * @param tess2 // * @param tess3 // */ // void visitFace(short tess1, short tess2, short tess3); // // /** // * Visit multiple faces at once. // * // * @param tessOrder // * short[]#length must be divisible by 3 // * @see #visitFace(short, short, short) // */ // default void visitFaces(short[] tessOrder) { // if (tessOrder.length % 3 != 0) { // throw new IllegalArgumentException(); // } // int maxI = tessOrder.length / 3; // for (int i = 0; i < maxI; i++) { // visitFace(tessOrder[i], tessOrder[i + 1], tessOrder[i + 2]); // } // } // // IMaterialVisitor visitTexture(); // // void visitEnd(); // } // // Path: src/main/java/com/github/worldsender/mcanm/common/exceptions/ModelFormatException.java // public class ModelFormatException extends IllegalArgumentException { // /** // * // */ // private static final long serialVersionUID = -4000239134878464297L; // // public ModelFormatException() { // super(); // } // // public ModelFormatException(String message) { // super(message); // } // // public ModelFormatException(Throwable cause) { // super(cause); // } // // public ModelFormatException(String message, Throwable cause) { // super(message, cause); // } // } // Path: src/main/java/com/github/worldsender/mcanm/client/mcanmmodel/stored/RawDataV2.java import java.io.DataInputStream; import java.io.IOException; import com.github.worldsender.mcanm.client.mcanmmodel.stored.parts.Material; import com.github.worldsender.mcanm.client.mcanmmodel.stored.parts.ModelPartV2; import com.github.worldsender.mcanm.client.mcanmmodel.visitor.IMaterialVisitor; import com.github.worldsender.mcanm.client.mcanmmodel.visitor.IModelVisitor; import com.github.worldsender.mcanm.client.mcanmmodel.visitor.IPartVisitor; import com.github.worldsender.mcanm.common.exceptions.ModelFormatException; package com.github.worldsender.mcanm.client.mcanmmodel.stored; public class RawDataV2 implements IVersionSpecificData { private ModelPartV2[] parts; private Material[] mats; @Override public void visitBy(IModelVisitor visitor) { for (ModelPartV2 part : parts) { IPartVisitor partVisitor = visitor.visitPart(part.name); partVisitor.visitTesselationPoints(part.points); partVisitor.visitFaces(part.indices); {
IMaterialVisitor matVisitor = partVisitor.visitTexture();
WorldSEnder/MCAnm
src/main/java/com/github/worldsender/mcanm/client/renderer/AnimatedObjAdapter.java
// Path: src/main/java/com/github/worldsender/mcanm/client/model/util/RenderPassInformation.java // public class RenderPassInformation extends ModelStateInformation implements IRenderPassInformation { // public static final Function<String, ResourceLocation> makeCachingTransform( // Function<String, ResourceLocation> cacheLoader) { // LoadingCache<String, ResourceLocation> cachedResourceLoc = CacheBuilder.newBuilder().maximumSize(100) // .build(new CacheLoader<String, ResourceLocation>() { // @Override // public ResourceLocation load(String key) { // return cacheLoader.apply(key); // } // }); // return cachedResourceLoc::getUnchecked; // } // // public static final Function<String, ResourceLocation> TRANSFORM_DIRECT = makeCachingTransform( // ResourceLocation::new); // /** // * This is the default texture rebinding, it just returns the given resource-location and as such does not change // * the bound texture. // */ // public static final Function<ResourceLocation, ResourceLocation> IDENTITY = Function.identity(); // // private Function<String, ResourceLocation> textureRemap; // // public RenderPassInformation() { // this.reset(); // } // // public RenderPassInformation( // float frame, // Optional<IAnimation> animation, // Optional<Predicate<String>> partPredicate, // Optional<Function<String, ResourceLocation>> resourceRemap) { // this.setFrame(frame).setAnimation(animation).setPartPredicate(partPredicate).setTextureTransform(resourceRemap); // } // // /** // * Resets this information to be reused. // */ // @Override // public void reset() { // super.reset(); // this.setTextureTransform(Optional.empty()); // } // // @Override // public ResourceLocation getActualResourceLocation(String in) { // return this.textureRemap.apply(in); // } // // @Override // public RenderPassInformation setAnimation(Optional<IAnimation> animation) { // super.setAnimation(animation); // return this; // } // // @Override // public RenderPassInformation setAnimation(IAnimation animation) { // super.setAnimation(animation); // return this; // } // // /** // * @param frame // * the frame to set // */ // @Override // public RenderPassInformation setFrame(float frame) { // super.setFrame(frame); // return this; // } // // /** // * @param partPredicate // * the partPredicate to set, Optional.empty() for RENDER_ALL // */ // @Override // public RenderPassInformation setPartPredicate(Optional<Predicate<String>> partPredicate) { // super.setPartPredicate(partPredicate); // return this; // } // // @Override // public RenderPassInformation setPartPredicate(Predicate<String> partPredicate) { // super.setPartPredicate(partPredicate); // return this; // } // // public RenderPassInformation setTextureTransform(Optional<Function<String, ResourceLocation>> textureRemap) { // return setTextureTransform(textureRemap.orElse(TRANSFORM_DIRECT)); // } // // public RenderPassInformation setTextureTransform(Function<String, ResourceLocation> textureRemap) { // this.textureRemap = Objects.requireNonNull(textureRemap); // return this; // } // }
import com.github.worldsender.mcanm.client.model.util.RenderPassInformation;
package com.github.worldsender.mcanm.client.renderer; /** * Kind of a default implementation for {@link IAnimatedObject} which means that the user isn't bothered as much. * * @author WorldSEnder * */ public abstract class AnimatedObjAdapter implements IAnimatedObject { @Override
// Path: src/main/java/com/github/worldsender/mcanm/client/model/util/RenderPassInformation.java // public class RenderPassInformation extends ModelStateInformation implements IRenderPassInformation { // public static final Function<String, ResourceLocation> makeCachingTransform( // Function<String, ResourceLocation> cacheLoader) { // LoadingCache<String, ResourceLocation> cachedResourceLoc = CacheBuilder.newBuilder().maximumSize(100) // .build(new CacheLoader<String, ResourceLocation>() { // @Override // public ResourceLocation load(String key) { // return cacheLoader.apply(key); // } // }); // return cachedResourceLoc::getUnchecked; // } // // public static final Function<String, ResourceLocation> TRANSFORM_DIRECT = makeCachingTransform( // ResourceLocation::new); // /** // * This is the default texture rebinding, it just returns the given resource-location and as such does not change // * the bound texture. // */ // public static final Function<ResourceLocation, ResourceLocation> IDENTITY = Function.identity(); // // private Function<String, ResourceLocation> textureRemap; // // public RenderPassInformation() { // this.reset(); // } // // public RenderPassInformation( // float frame, // Optional<IAnimation> animation, // Optional<Predicate<String>> partPredicate, // Optional<Function<String, ResourceLocation>> resourceRemap) { // this.setFrame(frame).setAnimation(animation).setPartPredicate(partPredicate).setTextureTransform(resourceRemap); // } // // /** // * Resets this information to be reused. // */ // @Override // public void reset() { // super.reset(); // this.setTextureTransform(Optional.empty()); // } // // @Override // public ResourceLocation getActualResourceLocation(String in) { // return this.textureRemap.apply(in); // } // // @Override // public RenderPassInformation setAnimation(Optional<IAnimation> animation) { // super.setAnimation(animation); // return this; // } // // @Override // public RenderPassInformation setAnimation(IAnimation animation) { // super.setAnimation(animation); // return this; // } // // /** // * @param frame // * the frame to set // */ // @Override // public RenderPassInformation setFrame(float frame) { // super.setFrame(frame); // return this; // } // // /** // * @param partPredicate // * the partPredicate to set, Optional.empty() for RENDER_ALL // */ // @Override // public RenderPassInformation setPartPredicate(Optional<Predicate<String>> partPredicate) { // super.setPartPredicate(partPredicate); // return this; // } // // @Override // public RenderPassInformation setPartPredicate(Predicate<String> partPredicate) { // super.setPartPredicate(partPredicate); // return this; // } // // public RenderPassInformation setTextureTransform(Optional<Function<String, ResourceLocation>> textureRemap) { // return setTextureTransform(textureRemap.orElse(TRANSFORM_DIRECT)); // } // // public RenderPassInformation setTextureTransform(Function<String, ResourceLocation> textureRemap) { // this.textureRemap = Objects.requireNonNull(textureRemap); // return this; // } // } // Path: src/main/java/com/github/worldsender/mcanm/client/renderer/AnimatedObjAdapter.java import com.github.worldsender.mcanm.client.model.util.RenderPassInformation; package com.github.worldsender.mcanm.client.renderer; /** * Kind of a default implementation for {@link IAnimatedObject} which means that the user isn't bothered as much. * * @author WorldSEnder * */ public abstract class AnimatedObjAdapter implements IAnimatedObject { @Override
public RenderPassInformation preRenderCallback(float subFrame, RenderPassInformation callback) {
WorldSEnder/MCAnm
src/main/java/com/github/worldsender/mcanm/common/skeleton/ISkeleton.java
// Path: src/main/java/com/github/worldsender/mcanm/common/animation/IAnimation.java // public interface IAnimation { // /** // * Describes a BoneTransformation, including rotation, translation and scaling. This class is opaque i.e. all // * getters and setters don't make defensive copies and states can be manipulated from the outside. // * // * @author WorldSEnder // * // */ // public static class BoneTransformation { // public static final BoneTransformation identity = new BoneTransformation(); // // private static Vector3f identityScale() { // return new Vector3f(1.0F, 1.0F, 1.0F); // } // // public final Matrix4f matrix; // // public BoneTransformation() { // this(null, null, null); // } // // public BoneTransformation(Vector3f translation, Quat4f quat) { // this(translation, quat, identityScale()); // } // // public BoneTransformation(Vector3f translation, Quat4f quat, Vector3f scale) { // if (quat == null) // quat = new Quat4f(); // if (translation == null) // translation = new Vector3f(); // if (scale == null) // scale = identityScale(); // this.matrix = Utils.fromRTS(quat, translation, scale, new Matrix4f()); // } // // public Matrix4f getMatrix() { // return matrix; // } // } // // /** // * Stores the bone's current {@link BoneTransformation} in transform(identified by name). <br> // * If the requested bone is not known to the animation transform is left untouched and this return // * <code>false</code>. Otherwise transform is set to the bone's current transform state. // * // * @param bone // * the name of the bone the matrix is requested // * @param frame // * the current frame in the animation // * @param transform // * the transform to set // * @return if a transformation has been set // */ // public boolean storeCurrentTransformation(String bone, float frame, BoneTransformation transform); // }
import com.github.worldsender.mcanm.common.animation.IAnimation; import net.minecraft.client.renderer.Tessellator;
package com.github.worldsender.mcanm.common.skeleton; public interface ISkeleton { public static final ISkeleton EMPTY = new ISkeleton() { @Override
// Path: src/main/java/com/github/worldsender/mcanm/common/animation/IAnimation.java // public interface IAnimation { // /** // * Describes a BoneTransformation, including rotation, translation and scaling. This class is opaque i.e. all // * getters and setters don't make defensive copies and states can be manipulated from the outside. // * // * @author WorldSEnder // * // */ // public static class BoneTransformation { // public static final BoneTransformation identity = new BoneTransformation(); // // private static Vector3f identityScale() { // return new Vector3f(1.0F, 1.0F, 1.0F); // } // // public final Matrix4f matrix; // // public BoneTransformation() { // this(null, null, null); // } // // public BoneTransformation(Vector3f translation, Quat4f quat) { // this(translation, quat, identityScale()); // } // // public BoneTransformation(Vector3f translation, Quat4f quat, Vector3f scale) { // if (quat == null) // quat = new Quat4f(); // if (translation == null) // translation = new Vector3f(); // if (scale == null) // scale = identityScale(); // this.matrix = Utils.fromRTS(quat, translation, scale, new Matrix4f()); // } // // public Matrix4f getMatrix() { // return matrix; // } // } // // /** // * Stores the bone's current {@link BoneTransformation} in transform(identified by name). <br> // * If the requested bone is not known to the animation transform is left untouched and this return // * <code>false</code>. Otherwise transform is set to the bone's current transform state. // * // * @param bone // * the name of the bone the matrix is requested // * @param frame // * the current frame in the animation // * @param transform // * the transform to set // * @return if a transformation has been set // */ // public boolean storeCurrentTransformation(String bone, float frame, BoneTransformation transform); // } // Path: src/main/java/com/github/worldsender/mcanm/common/skeleton/ISkeleton.java import com.github.worldsender.mcanm.common.animation.IAnimation; import net.minecraft.client.renderer.Tessellator; package com.github.worldsender.mcanm.common.skeleton; public interface ISkeleton { public static final ISkeleton EMPTY = new ISkeleton() { @Override
public void setup(IAnimation animation, float frame) {}
WorldSEnder/MCAnm
src/main/java/com/github/worldsender/mcanm/client/model/util/RenderPass.java
// Path: src/main/java/com/github/worldsender/mcanm/client/IRenderPass.java // public interface IRenderPass extends IRenderPassInformation { // /** // * Binds the resource-location given.<br> // * <b>WARNING</b> This does not transform the resourc-location via // * {@link #getActualResourceLocation(ResourceLocation)}. This has the be done before calling this method. // * // * @param resLoc // * the resource to bind // */ // void bindTexture(ResourceLocation resLoc); // } // // Path: src/main/java/com/github/worldsender/mcanm/client/model/IEntityRender.java // public interface IEntityRender<T extends EntityLiving> { // /** // * Retrieves the current animator // * // * @return // */ // IEntityAnimator<T> getAnimator(); // // /** // * Binds a texture // */ // void bindTextureFrom(ResourceLocation resLoc); // } // // Path: src/main/java/com/github/worldsender/mcanm/client/model/IRenderPassInformation.java // public interface IRenderPassInformation extends IModelStateInformation { // /** // * Retrieves the texture that should go into the texture slot slot // * // * @param slot // * the name of the texture slot getting polled // * @return the resource location of the texture to stick // */ // ResourceLocation getActualResourceLocation(String slot); // } // // Path: src/main/java/com/github/worldsender/mcanm/common/animation/IAnimation.java // public interface IAnimation { // /** // * Describes a BoneTransformation, including rotation, translation and scaling. This class is opaque i.e. all // * getters and setters don't make defensive copies and states can be manipulated from the outside. // * // * @author WorldSEnder // * // */ // public static class BoneTransformation { // public static final BoneTransformation identity = new BoneTransformation(); // // private static Vector3f identityScale() { // return new Vector3f(1.0F, 1.0F, 1.0F); // } // // public final Matrix4f matrix; // // public BoneTransformation() { // this(null, null, null); // } // // public BoneTransformation(Vector3f translation, Quat4f quat) { // this(translation, quat, identityScale()); // } // // public BoneTransformation(Vector3f translation, Quat4f quat, Vector3f scale) { // if (quat == null) // quat = new Quat4f(); // if (translation == null) // translation = new Vector3f(); // if (scale == null) // scale = identityScale(); // this.matrix = Utils.fromRTS(quat, translation, scale, new Matrix4f()); // } // // public Matrix4f getMatrix() { // return matrix; // } // } // // /** // * Stores the bone's current {@link BoneTransformation} in transform(identified by name). <br> // * If the requested bone is not known to the animation transform is left untouched and this return // * <code>false</code>. Otherwise transform is set to the bone's current transform state. // * // * @param bone // * the name of the bone the matrix is requested // * @param frame // * the current frame in the animation // * @param transform // * the transform to set // * @return if a transformation has been set // */ // public boolean storeCurrentTransformation(String bone, float frame, BoneTransformation transform); // }
import java.util.Objects; import com.github.worldsender.mcanm.client.IRenderPass; import com.github.worldsender.mcanm.client.model.IEntityRender; import com.github.worldsender.mcanm.client.model.IRenderPassInformation; import com.github.worldsender.mcanm.common.animation.IAnimation; import net.minecraft.entity.EntityLiving; import net.minecraft.util.ResourceLocation;
package com.github.worldsender.mcanm.client.model.util; /** * A collection of information neccessary to render the model. * * @author WorldSEnder * */ public class RenderPass<T extends EntityLiving> implements IRenderPass { private IRenderPassInformation userInfo;
// Path: src/main/java/com/github/worldsender/mcanm/client/IRenderPass.java // public interface IRenderPass extends IRenderPassInformation { // /** // * Binds the resource-location given.<br> // * <b>WARNING</b> This does not transform the resourc-location via // * {@link #getActualResourceLocation(ResourceLocation)}. This has the be done before calling this method. // * // * @param resLoc // * the resource to bind // */ // void bindTexture(ResourceLocation resLoc); // } // // Path: src/main/java/com/github/worldsender/mcanm/client/model/IEntityRender.java // public interface IEntityRender<T extends EntityLiving> { // /** // * Retrieves the current animator // * // * @return // */ // IEntityAnimator<T> getAnimator(); // // /** // * Binds a texture // */ // void bindTextureFrom(ResourceLocation resLoc); // } // // Path: src/main/java/com/github/worldsender/mcanm/client/model/IRenderPassInformation.java // public interface IRenderPassInformation extends IModelStateInformation { // /** // * Retrieves the texture that should go into the texture slot slot // * // * @param slot // * the name of the texture slot getting polled // * @return the resource location of the texture to stick // */ // ResourceLocation getActualResourceLocation(String slot); // } // // Path: src/main/java/com/github/worldsender/mcanm/common/animation/IAnimation.java // public interface IAnimation { // /** // * Describes a BoneTransformation, including rotation, translation and scaling. This class is opaque i.e. all // * getters and setters don't make defensive copies and states can be manipulated from the outside. // * // * @author WorldSEnder // * // */ // public static class BoneTransformation { // public static final BoneTransformation identity = new BoneTransformation(); // // private static Vector3f identityScale() { // return new Vector3f(1.0F, 1.0F, 1.0F); // } // // public final Matrix4f matrix; // // public BoneTransformation() { // this(null, null, null); // } // // public BoneTransformation(Vector3f translation, Quat4f quat) { // this(translation, quat, identityScale()); // } // // public BoneTransformation(Vector3f translation, Quat4f quat, Vector3f scale) { // if (quat == null) // quat = new Quat4f(); // if (translation == null) // translation = new Vector3f(); // if (scale == null) // scale = identityScale(); // this.matrix = Utils.fromRTS(quat, translation, scale, new Matrix4f()); // } // // public Matrix4f getMatrix() { // return matrix; // } // } // // /** // * Stores the bone's current {@link BoneTransformation} in transform(identified by name). <br> // * If the requested bone is not known to the animation transform is left untouched and this return // * <code>false</code>. Otherwise transform is set to the bone's current transform state. // * // * @param bone // * the name of the bone the matrix is requested // * @param frame // * the current frame in the animation // * @param transform // * the transform to set // * @return if a transformation has been set // */ // public boolean storeCurrentTransformation(String bone, float frame, BoneTransformation transform); // } // Path: src/main/java/com/github/worldsender/mcanm/client/model/util/RenderPass.java import java.util.Objects; import com.github.worldsender.mcanm.client.IRenderPass; import com.github.worldsender.mcanm.client.model.IEntityRender; import com.github.worldsender.mcanm.client.model.IRenderPassInformation; import com.github.worldsender.mcanm.common.animation.IAnimation; import net.minecraft.entity.EntityLiving; import net.minecraft.util.ResourceLocation; package com.github.worldsender.mcanm.client.model.util; /** * A collection of information neccessary to render the model. * * @author WorldSEnder * */ public class RenderPass<T extends EntityLiving> implements IRenderPass { private IRenderPassInformation userInfo;
private IEntityRender<T> render;
WorldSEnder/MCAnm
src/main/java/com/github/worldsender/mcanm/client/model/util/RenderPass.java
// Path: src/main/java/com/github/worldsender/mcanm/client/IRenderPass.java // public interface IRenderPass extends IRenderPassInformation { // /** // * Binds the resource-location given.<br> // * <b>WARNING</b> This does not transform the resourc-location via // * {@link #getActualResourceLocation(ResourceLocation)}. This has the be done before calling this method. // * // * @param resLoc // * the resource to bind // */ // void bindTexture(ResourceLocation resLoc); // } // // Path: src/main/java/com/github/worldsender/mcanm/client/model/IEntityRender.java // public interface IEntityRender<T extends EntityLiving> { // /** // * Retrieves the current animator // * // * @return // */ // IEntityAnimator<T> getAnimator(); // // /** // * Binds a texture // */ // void bindTextureFrom(ResourceLocation resLoc); // } // // Path: src/main/java/com/github/worldsender/mcanm/client/model/IRenderPassInformation.java // public interface IRenderPassInformation extends IModelStateInformation { // /** // * Retrieves the texture that should go into the texture slot slot // * // * @param slot // * the name of the texture slot getting polled // * @return the resource location of the texture to stick // */ // ResourceLocation getActualResourceLocation(String slot); // } // // Path: src/main/java/com/github/worldsender/mcanm/common/animation/IAnimation.java // public interface IAnimation { // /** // * Describes a BoneTransformation, including rotation, translation and scaling. This class is opaque i.e. all // * getters and setters don't make defensive copies and states can be manipulated from the outside. // * // * @author WorldSEnder // * // */ // public static class BoneTransformation { // public static final BoneTransformation identity = new BoneTransformation(); // // private static Vector3f identityScale() { // return new Vector3f(1.0F, 1.0F, 1.0F); // } // // public final Matrix4f matrix; // // public BoneTransformation() { // this(null, null, null); // } // // public BoneTransformation(Vector3f translation, Quat4f quat) { // this(translation, quat, identityScale()); // } // // public BoneTransformation(Vector3f translation, Quat4f quat, Vector3f scale) { // if (quat == null) // quat = new Quat4f(); // if (translation == null) // translation = new Vector3f(); // if (scale == null) // scale = identityScale(); // this.matrix = Utils.fromRTS(quat, translation, scale, new Matrix4f()); // } // // public Matrix4f getMatrix() { // return matrix; // } // } // // /** // * Stores the bone's current {@link BoneTransformation} in transform(identified by name). <br> // * If the requested bone is not known to the animation transform is left untouched and this return // * <code>false</code>. Otherwise transform is set to the bone's current transform state. // * // * @param bone // * the name of the bone the matrix is requested // * @param frame // * the current frame in the animation // * @param transform // * the transform to set // * @return if a transformation has been set // */ // public boolean storeCurrentTransformation(String bone, float frame, BoneTransformation transform); // }
import java.util.Objects; import com.github.worldsender.mcanm.client.IRenderPass; import com.github.worldsender.mcanm.client.model.IEntityRender; import com.github.worldsender.mcanm.client.model.IRenderPassInformation; import com.github.worldsender.mcanm.common.animation.IAnimation; import net.minecraft.entity.EntityLiving; import net.minecraft.util.ResourceLocation;
package com.github.worldsender.mcanm.client.model.util; /** * A collection of information neccessary to render the model. * * @author WorldSEnder * */ public class RenderPass<T extends EntityLiving> implements IRenderPass { private IRenderPassInformation userInfo; private IEntityRender<T> render; public RenderPass(IRenderPassInformation info, IEntityRender<T> renderer) { this.userInfo = Objects.requireNonNull(info); this.render = Objects.requireNonNull(renderer); } @Override
// Path: src/main/java/com/github/worldsender/mcanm/client/IRenderPass.java // public interface IRenderPass extends IRenderPassInformation { // /** // * Binds the resource-location given.<br> // * <b>WARNING</b> This does not transform the resourc-location via // * {@link #getActualResourceLocation(ResourceLocation)}. This has the be done before calling this method. // * // * @param resLoc // * the resource to bind // */ // void bindTexture(ResourceLocation resLoc); // } // // Path: src/main/java/com/github/worldsender/mcanm/client/model/IEntityRender.java // public interface IEntityRender<T extends EntityLiving> { // /** // * Retrieves the current animator // * // * @return // */ // IEntityAnimator<T> getAnimator(); // // /** // * Binds a texture // */ // void bindTextureFrom(ResourceLocation resLoc); // } // // Path: src/main/java/com/github/worldsender/mcanm/client/model/IRenderPassInformation.java // public interface IRenderPassInformation extends IModelStateInformation { // /** // * Retrieves the texture that should go into the texture slot slot // * // * @param slot // * the name of the texture slot getting polled // * @return the resource location of the texture to stick // */ // ResourceLocation getActualResourceLocation(String slot); // } // // Path: src/main/java/com/github/worldsender/mcanm/common/animation/IAnimation.java // public interface IAnimation { // /** // * Describes a BoneTransformation, including rotation, translation and scaling. This class is opaque i.e. all // * getters and setters don't make defensive copies and states can be manipulated from the outside. // * // * @author WorldSEnder // * // */ // public static class BoneTransformation { // public static final BoneTransformation identity = new BoneTransformation(); // // private static Vector3f identityScale() { // return new Vector3f(1.0F, 1.0F, 1.0F); // } // // public final Matrix4f matrix; // // public BoneTransformation() { // this(null, null, null); // } // // public BoneTransformation(Vector3f translation, Quat4f quat) { // this(translation, quat, identityScale()); // } // // public BoneTransformation(Vector3f translation, Quat4f quat, Vector3f scale) { // if (quat == null) // quat = new Quat4f(); // if (translation == null) // translation = new Vector3f(); // if (scale == null) // scale = identityScale(); // this.matrix = Utils.fromRTS(quat, translation, scale, new Matrix4f()); // } // // public Matrix4f getMatrix() { // return matrix; // } // } // // /** // * Stores the bone's current {@link BoneTransformation} in transform(identified by name). <br> // * If the requested bone is not known to the animation transform is left untouched and this return // * <code>false</code>. Otherwise transform is set to the bone's current transform state. // * // * @param bone // * the name of the bone the matrix is requested // * @param frame // * the current frame in the animation // * @param transform // * the transform to set // * @return if a transformation has been set // */ // public boolean storeCurrentTransformation(String bone, float frame, BoneTransformation transform); // } // Path: src/main/java/com/github/worldsender/mcanm/client/model/util/RenderPass.java import java.util.Objects; import com.github.worldsender.mcanm.client.IRenderPass; import com.github.worldsender.mcanm.client.model.IEntityRender; import com.github.worldsender.mcanm.client.model.IRenderPassInformation; import com.github.worldsender.mcanm.common.animation.IAnimation; import net.minecraft.entity.EntityLiving; import net.minecraft.util.ResourceLocation; package com.github.worldsender.mcanm.client.model.util; /** * A collection of information neccessary to render the model. * * @author WorldSEnder * */ public class RenderPass<T extends EntityLiving> implements IRenderPass { private IRenderPassInformation userInfo; private IEntityRender<T> render; public RenderPass(IRenderPassInformation info, IEntityRender<T> renderer) { this.userInfo = Objects.requireNonNull(info); this.render = Objects.requireNonNull(renderer); } @Override
public IAnimation getAnimation() {
WorldSEnder/MCAnm
src/main/java/com/github/worldsender/mcanm/common/skeleton/stored/RawDataV1.java
// Path: src/main/java/com/github/worldsender/mcanm/client/mcanmmodel/stored/parts/RawBone.java // public class RawBone { // public String name; // public Quat4f rotation; // public Vector3f offset; // /** Parent of this bone as array index. A value of 0xFF means no parent */ // public byte parent; // // public static RawBone readBoneFrom(DataInputStream dis) throws IOException { // RawBone bone = new RawBone(); // String name = Utils.readString(dis); // Quat4f quat = Utils.readQuat(dis); // Vector3f offset = Utils.readVector3f(dis); // bone.name = name; // bone.rotation = quat; // bone.offset = offset; // return bone; // } // // } // // Path: src/main/java/com/github/worldsender/mcanm/common/exceptions/ModelFormatException.java // public class ModelFormatException extends IllegalArgumentException { // /** // * // */ // private static final long serialVersionUID = -4000239134878464297L; // // public ModelFormatException() { // super(); // } // // public ModelFormatException(String message) { // super(message); // } // // public ModelFormatException(Throwable cause) { // super(cause); // } // // public ModelFormatException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/com/github/worldsender/mcanm/common/skeleton/visitor/IBoneVisitor.java // public interface IBoneVisitor { // void visitParent(byte parentIndex); // // void visitLocalOffset(Vector3f headPosition); // // void visitLocalRotation(Quat4f rotation); // // void visitEnd(); // } // // Path: src/main/java/com/github/worldsender/mcanm/common/skeleton/visitor/ISkeletonVisitor.java // public interface ISkeletonVisitor { // IBoneVisitor visitBone(String name); // // void visitEnd(); // }
import java.io.DataInputStream; import java.io.IOException; import java.util.HashSet; import java.util.Set; import com.github.worldsender.mcanm.client.mcanmmodel.stored.parts.RawBone; import com.github.worldsender.mcanm.common.exceptions.ModelFormatException; import com.github.worldsender.mcanm.common.skeleton.visitor.IBoneVisitor; import com.github.worldsender.mcanm.common.skeleton.visitor.ISkeletonVisitor;
package com.github.worldsender.mcanm.common.skeleton.stored; public class RawDataV1 implements IVersionSpecificData { private RawBone[] bones; @Override
// Path: src/main/java/com/github/worldsender/mcanm/client/mcanmmodel/stored/parts/RawBone.java // public class RawBone { // public String name; // public Quat4f rotation; // public Vector3f offset; // /** Parent of this bone as array index. A value of 0xFF means no parent */ // public byte parent; // // public static RawBone readBoneFrom(DataInputStream dis) throws IOException { // RawBone bone = new RawBone(); // String name = Utils.readString(dis); // Quat4f quat = Utils.readQuat(dis); // Vector3f offset = Utils.readVector3f(dis); // bone.name = name; // bone.rotation = quat; // bone.offset = offset; // return bone; // } // // } // // Path: src/main/java/com/github/worldsender/mcanm/common/exceptions/ModelFormatException.java // public class ModelFormatException extends IllegalArgumentException { // /** // * // */ // private static final long serialVersionUID = -4000239134878464297L; // // public ModelFormatException() { // super(); // } // // public ModelFormatException(String message) { // super(message); // } // // public ModelFormatException(Throwable cause) { // super(cause); // } // // public ModelFormatException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/com/github/worldsender/mcanm/common/skeleton/visitor/IBoneVisitor.java // public interface IBoneVisitor { // void visitParent(byte parentIndex); // // void visitLocalOffset(Vector3f headPosition); // // void visitLocalRotation(Quat4f rotation); // // void visitEnd(); // } // // Path: src/main/java/com/github/worldsender/mcanm/common/skeleton/visitor/ISkeletonVisitor.java // public interface ISkeletonVisitor { // IBoneVisitor visitBone(String name); // // void visitEnd(); // } // Path: src/main/java/com/github/worldsender/mcanm/common/skeleton/stored/RawDataV1.java import java.io.DataInputStream; import java.io.IOException; import java.util.HashSet; import java.util.Set; import com.github.worldsender.mcanm.client.mcanmmodel.stored.parts.RawBone; import com.github.worldsender.mcanm.common.exceptions.ModelFormatException; import com.github.worldsender.mcanm.common.skeleton.visitor.IBoneVisitor; import com.github.worldsender.mcanm.common.skeleton.visitor.ISkeletonVisitor; package com.github.worldsender.mcanm.common.skeleton.stored; public class RawDataV1 implements IVersionSpecificData { private RawBone[] bones; @Override
public void visitBy(ISkeletonVisitor visitor) {
WorldSEnder/MCAnm
src/main/java/com/github/worldsender/mcanm/common/skeleton/stored/RawDataV1.java
// Path: src/main/java/com/github/worldsender/mcanm/client/mcanmmodel/stored/parts/RawBone.java // public class RawBone { // public String name; // public Quat4f rotation; // public Vector3f offset; // /** Parent of this bone as array index. A value of 0xFF means no parent */ // public byte parent; // // public static RawBone readBoneFrom(DataInputStream dis) throws IOException { // RawBone bone = new RawBone(); // String name = Utils.readString(dis); // Quat4f quat = Utils.readQuat(dis); // Vector3f offset = Utils.readVector3f(dis); // bone.name = name; // bone.rotation = quat; // bone.offset = offset; // return bone; // } // // } // // Path: src/main/java/com/github/worldsender/mcanm/common/exceptions/ModelFormatException.java // public class ModelFormatException extends IllegalArgumentException { // /** // * // */ // private static final long serialVersionUID = -4000239134878464297L; // // public ModelFormatException() { // super(); // } // // public ModelFormatException(String message) { // super(message); // } // // public ModelFormatException(Throwable cause) { // super(cause); // } // // public ModelFormatException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/com/github/worldsender/mcanm/common/skeleton/visitor/IBoneVisitor.java // public interface IBoneVisitor { // void visitParent(byte parentIndex); // // void visitLocalOffset(Vector3f headPosition); // // void visitLocalRotation(Quat4f rotation); // // void visitEnd(); // } // // Path: src/main/java/com/github/worldsender/mcanm/common/skeleton/visitor/ISkeletonVisitor.java // public interface ISkeletonVisitor { // IBoneVisitor visitBone(String name); // // void visitEnd(); // }
import java.io.DataInputStream; import java.io.IOException; import java.util.HashSet; import java.util.Set; import com.github.worldsender.mcanm.client.mcanmmodel.stored.parts.RawBone; import com.github.worldsender.mcanm.common.exceptions.ModelFormatException; import com.github.worldsender.mcanm.common.skeleton.visitor.IBoneVisitor; import com.github.worldsender.mcanm.common.skeleton.visitor.ISkeletonVisitor;
package com.github.worldsender.mcanm.common.skeleton.stored; public class RawDataV1 implements IVersionSpecificData { private RawBone[] bones; @Override public void visitBy(ISkeletonVisitor visitor) { for (RawBone bone : bones) {
// Path: src/main/java/com/github/worldsender/mcanm/client/mcanmmodel/stored/parts/RawBone.java // public class RawBone { // public String name; // public Quat4f rotation; // public Vector3f offset; // /** Parent of this bone as array index. A value of 0xFF means no parent */ // public byte parent; // // public static RawBone readBoneFrom(DataInputStream dis) throws IOException { // RawBone bone = new RawBone(); // String name = Utils.readString(dis); // Quat4f quat = Utils.readQuat(dis); // Vector3f offset = Utils.readVector3f(dis); // bone.name = name; // bone.rotation = quat; // bone.offset = offset; // return bone; // } // // } // // Path: src/main/java/com/github/worldsender/mcanm/common/exceptions/ModelFormatException.java // public class ModelFormatException extends IllegalArgumentException { // /** // * // */ // private static final long serialVersionUID = -4000239134878464297L; // // public ModelFormatException() { // super(); // } // // public ModelFormatException(String message) { // super(message); // } // // public ModelFormatException(Throwable cause) { // super(cause); // } // // public ModelFormatException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/com/github/worldsender/mcanm/common/skeleton/visitor/IBoneVisitor.java // public interface IBoneVisitor { // void visitParent(byte parentIndex); // // void visitLocalOffset(Vector3f headPosition); // // void visitLocalRotation(Quat4f rotation); // // void visitEnd(); // } // // Path: src/main/java/com/github/worldsender/mcanm/common/skeleton/visitor/ISkeletonVisitor.java // public interface ISkeletonVisitor { // IBoneVisitor visitBone(String name); // // void visitEnd(); // } // Path: src/main/java/com/github/worldsender/mcanm/common/skeleton/stored/RawDataV1.java import java.io.DataInputStream; import java.io.IOException; import java.util.HashSet; import java.util.Set; import com.github.worldsender.mcanm.client.mcanmmodel.stored.parts.RawBone; import com.github.worldsender.mcanm.common.exceptions.ModelFormatException; import com.github.worldsender.mcanm.common.skeleton.visitor.IBoneVisitor; import com.github.worldsender.mcanm.common.skeleton.visitor.ISkeletonVisitor; package com.github.worldsender.mcanm.common.skeleton.stored; public class RawDataV1 implements IVersionSpecificData { private RawBone[] bones; @Override public void visitBy(ISkeletonVisitor visitor) { for (RawBone bone : bones) {
IBoneVisitor boneVisitor = visitor.visitBone(bone.name);
WorldSEnder/MCAnm
src/main/java/com/github/worldsender/mcanm/common/skeleton/stored/RawDataV1.java
// Path: src/main/java/com/github/worldsender/mcanm/client/mcanmmodel/stored/parts/RawBone.java // public class RawBone { // public String name; // public Quat4f rotation; // public Vector3f offset; // /** Parent of this bone as array index. A value of 0xFF means no parent */ // public byte parent; // // public static RawBone readBoneFrom(DataInputStream dis) throws IOException { // RawBone bone = new RawBone(); // String name = Utils.readString(dis); // Quat4f quat = Utils.readQuat(dis); // Vector3f offset = Utils.readVector3f(dis); // bone.name = name; // bone.rotation = quat; // bone.offset = offset; // return bone; // } // // } // // Path: src/main/java/com/github/worldsender/mcanm/common/exceptions/ModelFormatException.java // public class ModelFormatException extends IllegalArgumentException { // /** // * // */ // private static final long serialVersionUID = -4000239134878464297L; // // public ModelFormatException() { // super(); // } // // public ModelFormatException(String message) { // super(message); // } // // public ModelFormatException(Throwable cause) { // super(cause); // } // // public ModelFormatException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/com/github/worldsender/mcanm/common/skeleton/visitor/IBoneVisitor.java // public interface IBoneVisitor { // void visitParent(byte parentIndex); // // void visitLocalOffset(Vector3f headPosition); // // void visitLocalRotation(Quat4f rotation); // // void visitEnd(); // } // // Path: src/main/java/com/github/worldsender/mcanm/common/skeleton/visitor/ISkeletonVisitor.java // public interface ISkeletonVisitor { // IBoneVisitor visitBone(String name); // // void visitEnd(); // }
import java.io.DataInputStream; import java.io.IOException; import java.util.HashSet; import java.util.Set; import com.github.worldsender.mcanm.client.mcanmmodel.stored.parts.RawBone; import com.github.worldsender.mcanm.common.exceptions.ModelFormatException; import com.github.worldsender.mcanm.common.skeleton.visitor.IBoneVisitor; import com.github.worldsender.mcanm.common.skeleton.visitor.ISkeletonVisitor;
package com.github.worldsender.mcanm.common.skeleton.stored; public class RawDataV1 implements IVersionSpecificData { private RawBone[] bones; @Override public void visitBy(ISkeletonVisitor visitor) { for (RawBone bone : bones) { IBoneVisitor boneVisitor = visitor.visitBone(bone.name); if (bone.parent != 0xFF) { boneVisitor.visitParent(bone.parent); } boneVisitor.visitLocalOffset(bone.offset); boneVisitor.visitLocalRotation(bone.rotation); boneVisitor.visitEnd(); } }
// Path: src/main/java/com/github/worldsender/mcanm/client/mcanmmodel/stored/parts/RawBone.java // public class RawBone { // public String name; // public Quat4f rotation; // public Vector3f offset; // /** Parent of this bone as array index. A value of 0xFF means no parent */ // public byte parent; // // public static RawBone readBoneFrom(DataInputStream dis) throws IOException { // RawBone bone = new RawBone(); // String name = Utils.readString(dis); // Quat4f quat = Utils.readQuat(dis); // Vector3f offset = Utils.readVector3f(dis); // bone.name = name; // bone.rotation = quat; // bone.offset = offset; // return bone; // } // // } // // Path: src/main/java/com/github/worldsender/mcanm/common/exceptions/ModelFormatException.java // public class ModelFormatException extends IllegalArgumentException { // /** // * // */ // private static final long serialVersionUID = -4000239134878464297L; // // public ModelFormatException() { // super(); // } // // public ModelFormatException(String message) { // super(message); // } // // public ModelFormatException(Throwable cause) { // super(cause); // } // // public ModelFormatException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/com/github/worldsender/mcanm/common/skeleton/visitor/IBoneVisitor.java // public interface IBoneVisitor { // void visitParent(byte parentIndex); // // void visitLocalOffset(Vector3f headPosition); // // void visitLocalRotation(Quat4f rotation); // // void visitEnd(); // } // // Path: src/main/java/com/github/worldsender/mcanm/common/skeleton/visitor/ISkeletonVisitor.java // public interface ISkeletonVisitor { // IBoneVisitor visitBone(String name); // // void visitEnd(); // } // Path: src/main/java/com/github/worldsender/mcanm/common/skeleton/stored/RawDataV1.java import java.io.DataInputStream; import java.io.IOException; import java.util.HashSet; import java.util.Set; import com.github.worldsender.mcanm.client.mcanmmodel.stored.parts.RawBone; import com.github.worldsender.mcanm.common.exceptions.ModelFormatException; import com.github.worldsender.mcanm.common.skeleton.visitor.IBoneVisitor; import com.github.worldsender.mcanm.common.skeleton.visitor.ISkeletonVisitor; package com.github.worldsender.mcanm.common.skeleton.stored; public class RawDataV1 implements IVersionSpecificData { private RawBone[] bones; @Override public void visitBy(ISkeletonVisitor visitor) { for (RawBone bone : bones) { IBoneVisitor boneVisitor = visitor.visitBone(bone.name); if (bone.parent != 0xFF) { boneVisitor.visitParent(bone.parent); } boneVisitor.visitLocalOffset(bone.offset); boneVisitor.visitLocalRotation(bone.rotation); boneVisitor.visitEnd(); } }
public static final RawDataV1 loadFrom(DataInputStream dis) throws IOException, ModelFormatException {
WorldSEnder/MCAnm
src/main/java/com/github/worldsender/mcanm/client/config/MCAnmGUI.java
// Path: src/main/java/com/github/worldsender/mcanm/MCAnm.java // @Mod( // modid = Reference.core_modid, // name = Reference.core_modname, // version = Reference.core_modversion, // guiFactory = "com.github.worldsender.mcanm.client.config.MCAnmGuiFactory") // public class MCAnm { // /** // * Enables various visual outputs, e.g. the bones of models are rendered. // */ // public static final boolean isDebug; // static { // Object deobfEnv = Launch.blackboard.get("fml.deobfuscatedEnvironment"); // Boolean isDeobfEnv = deobfEnv instanceof Boolean ? (Boolean) deobfEnv : null; // isDebug = isDeobfEnv == null ? false : isDeobfEnv.booleanValue(); // } // // @Mod.Instance(Reference.core_modid) // public static MCAnm instance; // // @SidedProxy( // modId = Reference.core_modid, // clientSide = "com.github.worldsender.mcanm.client.ClientProxy", // serverSide = "com.github.worldsender.mcanm.server.ServerProxy") // public static Proxy proxy; // // private MCAnmConfiguration config; // private Logger logger; // // @Mod.EventHandler // public void preInit(FMLPreInitializationEvent pre) { // logger = pre.getModLog(); // config = new MCAnmConfiguration(pre.getSuggestedConfigurationFile()); // proxy.preInit(); // MinecraftForge.EVENT_BUS.register(this); // logger.info("Successfully loaded MC Animations"); // } // // @Mod.EventHandler // public void init(@SuppressWarnings("unused") FMLInitializationEvent event) { // if (isDebug) { // ResourceLocation ID_CUBE = new ResourceLocation("mcanm:cube"); // ResourceLocation ID_CUBE_V2 = new ResourceLocation("mcanm:cube2"); // EntityRegistry.registerModEntity(ID_CUBE, CubeEntity.class, "Cube", 0, this, 80, 1, true); // EntityRegistry.registerModEntity(ID_CUBE_V2, CubeEntityV2.class, "CubeV2", 1, this, 80, 1, true); // } // proxy.init(); // } // // @SubscribeEvent // public void onConfigChange(OnConfigChangedEvent occe) { // if (!occe.getModID().equals(Reference.core_modid)) // return; // config.onConfigChange(occe); // } // // public static MCAnmConfiguration configuration() { // return instance.getConfiguration(); // } // // public MCAnmConfiguration getConfiguration() { // return this.config; // } // // public static Logger logger() { // return instance.getLogger(); // } // // public Logger getLogger() { // return this.logger; // } // } // // Path: src/main/java/com/github/worldsender/mcanm/Reference.java // public class Reference { // // public static final String config_reload_enabled = "enableReload"; // public static final String gui_config_title = "mcanm.config.title"; // public static final String gui_config_reload_enabled = "mcanm.config.autoreload"; // public static final String[] model_suffix_list = { ".mhmd" }; // public static final String model_type = "model_type"; // // public static final String core_modid = "@modid@"; // public static final String core_modname = "@MODNAME@"; // public static final String core_modversion = "@VERSION@"; // }
import java.util.ArrayList; import java.util.List; import com.github.worldsender.mcanm.MCAnm; import com.github.worldsender.mcanm.Reference; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.resources.I18n; import net.minecraftforge.fml.client.config.GuiConfig; import net.minecraftforge.fml.client.config.IConfigElement;
package com.github.worldsender.mcanm.client.config; public class MCAnmGUI extends GuiConfig { public MCAnmGUI(GuiScreen parent) {
// Path: src/main/java/com/github/worldsender/mcanm/MCAnm.java // @Mod( // modid = Reference.core_modid, // name = Reference.core_modname, // version = Reference.core_modversion, // guiFactory = "com.github.worldsender.mcanm.client.config.MCAnmGuiFactory") // public class MCAnm { // /** // * Enables various visual outputs, e.g. the bones of models are rendered. // */ // public static final boolean isDebug; // static { // Object deobfEnv = Launch.blackboard.get("fml.deobfuscatedEnvironment"); // Boolean isDeobfEnv = deobfEnv instanceof Boolean ? (Boolean) deobfEnv : null; // isDebug = isDeobfEnv == null ? false : isDeobfEnv.booleanValue(); // } // // @Mod.Instance(Reference.core_modid) // public static MCAnm instance; // // @SidedProxy( // modId = Reference.core_modid, // clientSide = "com.github.worldsender.mcanm.client.ClientProxy", // serverSide = "com.github.worldsender.mcanm.server.ServerProxy") // public static Proxy proxy; // // private MCAnmConfiguration config; // private Logger logger; // // @Mod.EventHandler // public void preInit(FMLPreInitializationEvent pre) { // logger = pre.getModLog(); // config = new MCAnmConfiguration(pre.getSuggestedConfigurationFile()); // proxy.preInit(); // MinecraftForge.EVENT_BUS.register(this); // logger.info("Successfully loaded MC Animations"); // } // // @Mod.EventHandler // public void init(@SuppressWarnings("unused") FMLInitializationEvent event) { // if (isDebug) { // ResourceLocation ID_CUBE = new ResourceLocation("mcanm:cube"); // ResourceLocation ID_CUBE_V2 = new ResourceLocation("mcanm:cube2"); // EntityRegistry.registerModEntity(ID_CUBE, CubeEntity.class, "Cube", 0, this, 80, 1, true); // EntityRegistry.registerModEntity(ID_CUBE_V2, CubeEntityV2.class, "CubeV2", 1, this, 80, 1, true); // } // proxy.init(); // } // // @SubscribeEvent // public void onConfigChange(OnConfigChangedEvent occe) { // if (!occe.getModID().equals(Reference.core_modid)) // return; // config.onConfigChange(occe); // } // // public static MCAnmConfiguration configuration() { // return instance.getConfiguration(); // } // // public MCAnmConfiguration getConfiguration() { // return this.config; // } // // public static Logger logger() { // return instance.getLogger(); // } // // public Logger getLogger() { // return this.logger; // } // } // // Path: src/main/java/com/github/worldsender/mcanm/Reference.java // public class Reference { // // public static final String config_reload_enabled = "enableReload"; // public static final String gui_config_title = "mcanm.config.title"; // public static final String gui_config_reload_enabled = "mcanm.config.autoreload"; // public static final String[] model_suffix_list = { ".mhmd" }; // public static final String model_type = "model_type"; // // public static final String core_modid = "@modid@"; // public static final String core_modname = "@MODNAME@"; // public static final String core_modversion = "@VERSION@"; // } // Path: src/main/java/com/github/worldsender/mcanm/client/config/MCAnmGUI.java import java.util.ArrayList; import java.util.List; import com.github.worldsender.mcanm.MCAnm; import com.github.worldsender.mcanm.Reference; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.resources.I18n; import net.minecraftforge.fml.client.config.GuiConfig; import net.minecraftforge.fml.client.config.IConfigElement; package com.github.worldsender.mcanm.client.config; public class MCAnmGUI extends GuiConfig { public MCAnmGUI(GuiScreen parent) {
super(parent, getConfigElements(), Reference.core_modid, false, false, I18n.format(Reference.gui_config_title));
WorldSEnder/MCAnm
src/main/java/com/github/worldsender/mcanm/client/config/MCAnmGUI.java
// Path: src/main/java/com/github/worldsender/mcanm/MCAnm.java // @Mod( // modid = Reference.core_modid, // name = Reference.core_modname, // version = Reference.core_modversion, // guiFactory = "com.github.worldsender.mcanm.client.config.MCAnmGuiFactory") // public class MCAnm { // /** // * Enables various visual outputs, e.g. the bones of models are rendered. // */ // public static final boolean isDebug; // static { // Object deobfEnv = Launch.blackboard.get("fml.deobfuscatedEnvironment"); // Boolean isDeobfEnv = deobfEnv instanceof Boolean ? (Boolean) deobfEnv : null; // isDebug = isDeobfEnv == null ? false : isDeobfEnv.booleanValue(); // } // // @Mod.Instance(Reference.core_modid) // public static MCAnm instance; // // @SidedProxy( // modId = Reference.core_modid, // clientSide = "com.github.worldsender.mcanm.client.ClientProxy", // serverSide = "com.github.worldsender.mcanm.server.ServerProxy") // public static Proxy proxy; // // private MCAnmConfiguration config; // private Logger logger; // // @Mod.EventHandler // public void preInit(FMLPreInitializationEvent pre) { // logger = pre.getModLog(); // config = new MCAnmConfiguration(pre.getSuggestedConfigurationFile()); // proxy.preInit(); // MinecraftForge.EVENT_BUS.register(this); // logger.info("Successfully loaded MC Animations"); // } // // @Mod.EventHandler // public void init(@SuppressWarnings("unused") FMLInitializationEvent event) { // if (isDebug) { // ResourceLocation ID_CUBE = new ResourceLocation("mcanm:cube"); // ResourceLocation ID_CUBE_V2 = new ResourceLocation("mcanm:cube2"); // EntityRegistry.registerModEntity(ID_CUBE, CubeEntity.class, "Cube", 0, this, 80, 1, true); // EntityRegistry.registerModEntity(ID_CUBE_V2, CubeEntityV2.class, "CubeV2", 1, this, 80, 1, true); // } // proxy.init(); // } // // @SubscribeEvent // public void onConfigChange(OnConfigChangedEvent occe) { // if (!occe.getModID().equals(Reference.core_modid)) // return; // config.onConfigChange(occe); // } // // public static MCAnmConfiguration configuration() { // return instance.getConfiguration(); // } // // public MCAnmConfiguration getConfiguration() { // return this.config; // } // // public static Logger logger() { // return instance.getLogger(); // } // // public Logger getLogger() { // return this.logger; // } // } // // Path: src/main/java/com/github/worldsender/mcanm/Reference.java // public class Reference { // // public static final String config_reload_enabled = "enableReload"; // public static final String gui_config_title = "mcanm.config.title"; // public static final String gui_config_reload_enabled = "mcanm.config.autoreload"; // public static final String[] model_suffix_list = { ".mhmd" }; // public static final String model_type = "model_type"; // // public static final String core_modid = "@modid@"; // public static final String core_modname = "@MODNAME@"; // public static final String core_modversion = "@VERSION@"; // }
import java.util.ArrayList; import java.util.List; import com.github.worldsender.mcanm.MCAnm; import com.github.worldsender.mcanm.Reference; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.resources.I18n; import net.minecraftforge.fml.client.config.GuiConfig; import net.minecraftforge.fml.client.config.IConfigElement;
package com.github.worldsender.mcanm.client.config; public class MCAnmGUI extends GuiConfig { public MCAnmGUI(GuiScreen parent) { super(parent, getConfigElements(), Reference.core_modid, false, false, I18n.format(Reference.gui_config_title)); } private static List<IConfigElement> getConfigElements() { List<IConfigElement> list = new ArrayList<>();
// Path: src/main/java/com/github/worldsender/mcanm/MCAnm.java // @Mod( // modid = Reference.core_modid, // name = Reference.core_modname, // version = Reference.core_modversion, // guiFactory = "com.github.worldsender.mcanm.client.config.MCAnmGuiFactory") // public class MCAnm { // /** // * Enables various visual outputs, e.g. the bones of models are rendered. // */ // public static final boolean isDebug; // static { // Object deobfEnv = Launch.blackboard.get("fml.deobfuscatedEnvironment"); // Boolean isDeobfEnv = deobfEnv instanceof Boolean ? (Boolean) deobfEnv : null; // isDebug = isDeobfEnv == null ? false : isDeobfEnv.booleanValue(); // } // // @Mod.Instance(Reference.core_modid) // public static MCAnm instance; // // @SidedProxy( // modId = Reference.core_modid, // clientSide = "com.github.worldsender.mcanm.client.ClientProxy", // serverSide = "com.github.worldsender.mcanm.server.ServerProxy") // public static Proxy proxy; // // private MCAnmConfiguration config; // private Logger logger; // // @Mod.EventHandler // public void preInit(FMLPreInitializationEvent pre) { // logger = pre.getModLog(); // config = new MCAnmConfiguration(pre.getSuggestedConfigurationFile()); // proxy.preInit(); // MinecraftForge.EVENT_BUS.register(this); // logger.info("Successfully loaded MC Animations"); // } // // @Mod.EventHandler // public void init(@SuppressWarnings("unused") FMLInitializationEvent event) { // if (isDebug) { // ResourceLocation ID_CUBE = new ResourceLocation("mcanm:cube"); // ResourceLocation ID_CUBE_V2 = new ResourceLocation("mcanm:cube2"); // EntityRegistry.registerModEntity(ID_CUBE, CubeEntity.class, "Cube", 0, this, 80, 1, true); // EntityRegistry.registerModEntity(ID_CUBE_V2, CubeEntityV2.class, "CubeV2", 1, this, 80, 1, true); // } // proxy.init(); // } // // @SubscribeEvent // public void onConfigChange(OnConfigChangedEvent occe) { // if (!occe.getModID().equals(Reference.core_modid)) // return; // config.onConfigChange(occe); // } // // public static MCAnmConfiguration configuration() { // return instance.getConfiguration(); // } // // public MCAnmConfiguration getConfiguration() { // return this.config; // } // // public static Logger logger() { // return instance.getLogger(); // } // // public Logger getLogger() { // return this.logger; // } // } // // Path: src/main/java/com/github/worldsender/mcanm/Reference.java // public class Reference { // // public static final String config_reload_enabled = "enableReload"; // public static final String gui_config_title = "mcanm.config.title"; // public static final String gui_config_reload_enabled = "mcanm.config.autoreload"; // public static final String[] model_suffix_list = { ".mhmd" }; // public static final String model_type = "model_type"; // // public static final String core_modid = "@modid@"; // public static final String core_modname = "@MODNAME@"; // public static final String core_modversion = "@VERSION@"; // } // Path: src/main/java/com/github/worldsender/mcanm/client/config/MCAnmGUI.java import java.util.ArrayList; import java.util.List; import com.github.worldsender.mcanm.MCAnm; import com.github.worldsender.mcanm.Reference; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.resources.I18n; import net.minecraftforge.fml.client.config.GuiConfig; import net.minecraftforge.fml.client.config.IConfigElement; package com.github.worldsender.mcanm.client.config; public class MCAnmGUI extends GuiConfig { public MCAnmGUI(GuiScreen parent) { super(parent, getConfigElements(), Reference.core_modid, false, false, I18n.format(Reference.gui_config_title)); } private static List<IConfigElement> getConfigElements() { List<IConfigElement> list = new ArrayList<>();
MCAnm.configuration().addPropertiesToDisplayList(list);
WorldSEnder/MCAnm
src/main/java/com/github/worldsender/mcanm/common/animation/parts/Spline.java
// Path: src/main/java/com/github/worldsender/mcanm/common/exceptions/ModelFormatException.java // public class ModelFormatException extends IllegalArgumentException { // /** // * // */ // private static final long serialVersionUID = -4000239134878464297L; // // public ModelFormatException() { // super(); // } // // public ModelFormatException(String message) { // super(message); // } // // public ModelFormatException(Throwable cause) { // super(cause); // } // // public ModelFormatException(String message, Throwable cause) { // super(message, cause); // } // }
import java.io.DataInputStream; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.lwjgl.util.vector.Vector2f; import com.github.worldsender.mcanm.common.exceptions.ModelFormatException;
/** * Registers an {@link IEaseInSplineFactory} for the descriminator byte given. * * @param descriminator * the descriminator byte * @param factory * the factory, can't be <code>null</code> * @return a previously registered factory, if any */ public static IEaseInSplineFactory registerEaseInFactory(byte descriminator, IEaseInSplineFactory factory) { if (factory == null) throw new IllegalArgumentException("Factory can't be null"); return ease_in_factories.put(descriminator, factory); } /** * Constructs a new spline from the read descriminator byte using previously registered with * {@link #registerEaseInFactory(byte, IEaseInSplineFactory)}. This will be the spline from -infinity to right.x. * * @param descr * the read descriminator byte * @param right * right point of this spline * @param dis * a {@link DataInputStream} to read additional data from * @return * @throws ModelFormatException * @throws IOException */ public static Spline easeIn(byte descr, Vector2f right, DataInputStream dis)
// Path: src/main/java/com/github/worldsender/mcanm/common/exceptions/ModelFormatException.java // public class ModelFormatException extends IllegalArgumentException { // /** // * // */ // private static final long serialVersionUID = -4000239134878464297L; // // public ModelFormatException() { // super(); // } // // public ModelFormatException(String message) { // super(message); // } // // public ModelFormatException(Throwable cause) { // super(cause); // } // // public ModelFormatException(String message, Throwable cause) { // super(message, cause); // } // } // Path: src/main/java/com/github/worldsender/mcanm/common/animation/parts/Spline.java import java.io.DataInputStream; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.lwjgl.util.vector.Vector2f; import com.github.worldsender.mcanm.common.exceptions.ModelFormatException; /** * Registers an {@link IEaseInSplineFactory} for the descriminator byte given. * * @param descriminator * the descriminator byte * @param factory * the factory, can't be <code>null</code> * @return a previously registered factory, if any */ public static IEaseInSplineFactory registerEaseInFactory(byte descriminator, IEaseInSplineFactory factory) { if (factory == null) throw new IllegalArgumentException("Factory can't be null"); return ease_in_factories.put(descriminator, factory); } /** * Constructs a new spline from the read descriminator byte using previously registered with * {@link #registerEaseInFactory(byte, IEaseInSplineFactory)}. This will be the spline from -infinity to right.x. * * @param descr * the read descriminator byte * @param right * right point of this spline * @param dis * a {@link DataInputStream} to read additional data from * @return * @throws ModelFormatException * @throws IOException */ public static Spline easeIn(byte descr, Vector2f right, DataInputStream dis)
throws ModelFormatException,
google/Accessibility-Test-Framework-for-Android
src/main/java/com/google/android/apps/common/testing/accessibility/framework/AnnouncementEventCheck.java
// Path: src/main/java/com/google/android/apps/common/testing/accessibility/framework/AccessibilityCheckResult.java // public enum AccessibilityCheckResultType { // /** Clearly an accessibility bug, for example no speakable text on a clicked button */ // ERROR(ResultTypeProto.ERROR), // /** // * Potentially an accessibility bug, for example finding another view with the same speakable // * text as a clicked view // */ // WARNING(ResultTypeProto.WARNING), // /** // * Information that may be helpful when evaluating accessibility, for example a listing of all // * speakable text in a view hierarchy in the traversal order used by an accessibility service. // */ // INFO(ResultTypeProto.INFO), // /** // * Indication that a potential issue was identified, but it was resolved as not an accessibility // * problem. // */ // RESOLVED(ResultTypeProto.RESOLVED), // /** A signal that the check was not run at all (ex. because the API level was too low) */ // NOT_RUN(ResultTypeProto.NOT_RUN), // /** // * A result that has been explicitly suppressed from throwing any Exceptions, used to allow for // * known issues. // */ // SUPPRESSED(ResultTypeProto.SUPPRESSED); // // private static final Map<Integer, AccessibilityCheckResultType> PROTO_NUMBER_MAP = // new HashMap<>(); // // static { // for (AccessibilityCheckResultType type : values()) { // PROTO_NUMBER_MAP.put(type.protoNumber, type); // } // } // // final int protoNumber; // // private AccessibilityCheckResultType(ResultTypeProto proto) { // this.protoNumber = proto.getNumber(); // } // // public static AccessibilityCheckResultType fromProto(ResultTypeProto proto) { // AccessibilityCheckResultType type = PROTO_NUMBER_MAP.get(proto.getNumber()); // checkArgument( // (type != null), // "Failed to create AccessibilityCheckResultType from proto with unknown value: %s", // proto.getNumber()); // return checkNotNull(type); // } // // public ResultTypeProto toProto() { // return ResultTypeProto.forNumber(protoNumber); // } // } // // Path: src/main/java/com/google/android/apps/common/testing/accessibility/framework/strings/StringManager.java // public final class StringManager { // // private static final String STRINGS_PACKAGE_NAME = // "com.google.android.apps.common.testing.accessibility.framework"; // private static final String STRINGS_FILE_NAME = "strings"; // private static @Nullable ResourceBundleProvider resourceBundleProvider; // // private StringManager() { // } // // /** // * Override the default resource bundle used by {@link StringManager}. If no provider is set, a // * default ResourceBundle will be used. // * // * <p>Example usage : If Accessibility Testing Framework is used outside the // * AndroidXmlResourceBundle environment or if the ClassLoader does not recognize the xml in // * specific package {@link #STRINGS_PACKAGE_NAME}, use this to override the resource provider. // */ // public static void setResourceBundleProvider(ResourceBundleProvider provider) { // resourceBundleProvider = provider; // } // // /** // * @param locale the desired locale // * @param name the name of the {@link String} to get from properties // * @return a localized {@link String} corresponding to the given name and locale // * @throws MissingResourceException if the string is not found // */ // public static String getString(Locale locale, String name) { // return getResourceBundle(locale).getString(name); // } // // private static ResourceBundle getResourceBundle(Locale locale) { // if (resourceBundleProvider != null) { // return resourceBundleProvider.getResourceBundle(locale); // } // // // ResourceBundle handles necessary caching. // try { // // Try to load the resources from under the package directory. This is location used for // // resource files in JAR files within Google. // return ResourceBundle.getBundle( // AndroidXMLResourceBundle.Control.getBaseName(STRINGS_PACKAGE_NAME, STRINGS_FILE_NAME), // locale, // checkNotNull(StringManager.class.getClassLoader()), // new AndroidXMLResourceBundle.Control()); // } catch (MissingResourceException e) { // // // If that doesn't work, try again, this time without the package name. This is the location // // used for assets in an AAR file. // return ResourceBundle.getBundle( // AndroidXMLResourceBundle.Control.getBaseName("", STRINGS_FILE_NAME), // locale, // checkNotNull(StringManager.class.getClassLoader()), // new AndroidXMLResourceBundle.Control()); // } // } // // /** // * Provider for resource bundle. Use this to override the default resource bundle to use in {@link // * StringManager}. // */ // public interface ResourceBundleProvider { // // /** Returns {@link ResourceBundle} that is suitable for the env, and the ClassLoader. */ // ResourceBundle getResourceBundle(Locale locale); // } // }
import android.view.View; import android.view.accessibility.AccessibilityEvent; import com.google.android.apps.common.testing.accessibility.framework.AccessibilityCheckResult.AccessibilityCheckResultType; import com.google.android.apps.common.testing.accessibility.framework.strings.StringManager; import com.google.common.collect.ImmutableList; import java.util.List; import java.util.Locale;
/* * Copyright (C) 2015 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.common.testing.accessibility.framework; /** * Check which may be used to flag use of {@link View#announceForAccessibility(CharSequence)} or * dispatch of {@link AccessibilityEvent}s of type {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}. The * use of these events, expect in specific situations, can be disruptive to the user. */ public class AnnouncementEventCheck extends AccessibilityEventCheck { @Override public boolean shouldHandleEvent(AccessibilityEvent event) { return (event != null) && (event.getEventType() == AccessibilityEvent.TYPE_ANNOUNCEMENT); } @Override public List<AccessibilityEventCheckResult> runCheckOnEvent(AccessibilityEvent event) { String message =
// Path: src/main/java/com/google/android/apps/common/testing/accessibility/framework/AccessibilityCheckResult.java // public enum AccessibilityCheckResultType { // /** Clearly an accessibility bug, for example no speakable text on a clicked button */ // ERROR(ResultTypeProto.ERROR), // /** // * Potentially an accessibility bug, for example finding another view with the same speakable // * text as a clicked view // */ // WARNING(ResultTypeProto.WARNING), // /** // * Information that may be helpful when evaluating accessibility, for example a listing of all // * speakable text in a view hierarchy in the traversal order used by an accessibility service. // */ // INFO(ResultTypeProto.INFO), // /** // * Indication that a potential issue was identified, but it was resolved as not an accessibility // * problem. // */ // RESOLVED(ResultTypeProto.RESOLVED), // /** A signal that the check was not run at all (ex. because the API level was too low) */ // NOT_RUN(ResultTypeProto.NOT_RUN), // /** // * A result that has been explicitly suppressed from throwing any Exceptions, used to allow for // * known issues. // */ // SUPPRESSED(ResultTypeProto.SUPPRESSED); // // private static final Map<Integer, AccessibilityCheckResultType> PROTO_NUMBER_MAP = // new HashMap<>(); // // static { // for (AccessibilityCheckResultType type : values()) { // PROTO_NUMBER_MAP.put(type.protoNumber, type); // } // } // // final int protoNumber; // // private AccessibilityCheckResultType(ResultTypeProto proto) { // this.protoNumber = proto.getNumber(); // } // // public static AccessibilityCheckResultType fromProto(ResultTypeProto proto) { // AccessibilityCheckResultType type = PROTO_NUMBER_MAP.get(proto.getNumber()); // checkArgument( // (type != null), // "Failed to create AccessibilityCheckResultType from proto with unknown value: %s", // proto.getNumber()); // return checkNotNull(type); // } // // public ResultTypeProto toProto() { // return ResultTypeProto.forNumber(protoNumber); // } // } // // Path: src/main/java/com/google/android/apps/common/testing/accessibility/framework/strings/StringManager.java // public final class StringManager { // // private static final String STRINGS_PACKAGE_NAME = // "com.google.android.apps.common.testing.accessibility.framework"; // private static final String STRINGS_FILE_NAME = "strings"; // private static @Nullable ResourceBundleProvider resourceBundleProvider; // // private StringManager() { // } // // /** // * Override the default resource bundle used by {@link StringManager}. If no provider is set, a // * default ResourceBundle will be used. // * // * <p>Example usage : If Accessibility Testing Framework is used outside the // * AndroidXmlResourceBundle environment or if the ClassLoader does not recognize the xml in // * specific package {@link #STRINGS_PACKAGE_NAME}, use this to override the resource provider. // */ // public static void setResourceBundleProvider(ResourceBundleProvider provider) { // resourceBundleProvider = provider; // } // // /** // * @param locale the desired locale // * @param name the name of the {@link String} to get from properties // * @return a localized {@link String} corresponding to the given name and locale // * @throws MissingResourceException if the string is not found // */ // public static String getString(Locale locale, String name) { // return getResourceBundle(locale).getString(name); // } // // private static ResourceBundle getResourceBundle(Locale locale) { // if (resourceBundleProvider != null) { // return resourceBundleProvider.getResourceBundle(locale); // } // // // ResourceBundle handles necessary caching. // try { // // Try to load the resources from under the package directory. This is location used for // // resource files in JAR files within Google. // return ResourceBundle.getBundle( // AndroidXMLResourceBundle.Control.getBaseName(STRINGS_PACKAGE_NAME, STRINGS_FILE_NAME), // locale, // checkNotNull(StringManager.class.getClassLoader()), // new AndroidXMLResourceBundle.Control()); // } catch (MissingResourceException e) { // // // If that doesn't work, try again, this time without the package name. This is the location // // used for assets in an AAR file. // return ResourceBundle.getBundle( // AndroidXMLResourceBundle.Control.getBaseName("", STRINGS_FILE_NAME), // locale, // checkNotNull(StringManager.class.getClassLoader()), // new AndroidXMLResourceBundle.Control()); // } // } // // /** // * Provider for resource bundle. Use this to override the default resource bundle to use in {@link // * StringManager}. // */ // public interface ResourceBundleProvider { // // /** Returns {@link ResourceBundle} that is suitable for the env, and the ClassLoader. */ // ResourceBundle getResourceBundle(Locale locale); // } // } // Path: src/main/java/com/google/android/apps/common/testing/accessibility/framework/AnnouncementEventCheck.java import android.view.View; import android.view.accessibility.AccessibilityEvent; import com.google.android.apps.common.testing.accessibility.framework.AccessibilityCheckResult.AccessibilityCheckResultType; import com.google.android.apps.common.testing.accessibility.framework.strings.StringManager; import com.google.common.collect.ImmutableList; import java.util.List; import java.util.Locale; /* * Copyright (C) 2015 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.common.testing.accessibility.framework; /** * Check which may be used to flag use of {@link View#announceForAccessibility(CharSequence)} or * dispatch of {@link AccessibilityEvent}s of type {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}. The * use of these events, expect in specific situations, can be disruptive to the user. */ public class AnnouncementEventCheck extends AccessibilityEventCheck { @Override public boolean shouldHandleEvent(AccessibilityEvent event) { return (event != null) && (event.getEventType() == AccessibilityEvent.TYPE_ANNOUNCEMENT); } @Override public List<AccessibilityEventCheckResult> runCheckOnEvent(AccessibilityEvent event) { String message =
StringManager.getString(Locale.getDefault(), "result_message_disruptive_announcement");
google/Accessibility-Test-Framework-for-Android
src/main/java/com/google/android/apps/common/testing/accessibility/framework/AccessibilityCheckResultBaseUtils.java
// Path: src/main/java/com/google/android/apps/common/testing/accessibility/framework/AccessibilityCheckResult.java // public enum AccessibilityCheckResultType { // /** Clearly an accessibility bug, for example no speakable text on a clicked button */ // ERROR(ResultTypeProto.ERROR), // /** // * Potentially an accessibility bug, for example finding another view with the same speakable // * text as a clicked view // */ // WARNING(ResultTypeProto.WARNING), // /** // * Information that may be helpful when evaluating accessibility, for example a listing of all // * speakable text in a view hierarchy in the traversal order used by an accessibility service. // */ // INFO(ResultTypeProto.INFO), // /** // * Indication that a potential issue was identified, but it was resolved as not an accessibility // * problem. // */ // RESOLVED(ResultTypeProto.RESOLVED), // /** A signal that the check was not run at all (ex. because the API level was too low) */ // NOT_RUN(ResultTypeProto.NOT_RUN), // /** // * A result that has been explicitly suppressed from throwing any Exceptions, used to allow for // * known issues. // */ // SUPPRESSED(ResultTypeProto.SUPPRESSED); // // private static final Map<Integer, AccessibilityCheckResultType> PROTO_NUMBER_MAP = // new HashMap<>(); // // static { // for (AccessibilityCheckResultType type : values()) { // PROTO_NUMBER_MAP.put(type.protoNumber, type); // } // } // // final int protoNumber; // // private AccessibilityCheckResultType(ResultTypeProto proto) { // this.protoNumber = proto.getNumber(); // } // // public static AccessibilityCheckResultType fromProto(ResultTypeProto proto) { // AccessibilityCheckResultType type = PROTO_NUMBER_MAP.get(proto.getNumber()); // checkArgument( // (type != null), // "Failed to create AccessibilityCheckResultType from proto with unknown value: %s", // proto.getNumber()); // return checkNotNull(type); // } // // public ResultTypeProto toProto() { // return ResultTypeProto.forNumber(protoNumber); // } // }
import com.google.android.apps.common.testing.accessibility.framework.AccessibilityCheckResult.AccessibilityCheckResultType; import com.google.common.collect.ImmutableBiMap; import java.util.ArrayList; import java.util.List; import java.util.Set; import org.checkerframework.checker.nullness.qual.Nullable; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.Matchers; import org.hamcrest.TypeSafeMatcher;
/* * Copyright (C) 2014 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.common.testing.accessibility.framework; /** * Utility class for dealing with {@code AccessibilityCheckResult}s, without any dependency upon * Android classes. * * <p>This duplicates some of the methods in {@code AccessibilityCheckResultUtils} in order to * support separate Android and Java build targets while maintaining API compatibility. */ public final class AccessibilityCheckResultBaseUtils { private AccessibilityCheckResultBaseUtils() {} /** * Takes a list of {@code AccessibilityCheckResult}s and returns a list with only results obtained * from the given {@code AccessibilityCheck}. * <p> * NOTE: This method explicitly does not take subtypes of {@code checkClass} into account when * filtering results. * * @param results a list of {@code AccessibilityCheckResult}s * @param checkClass the {@code Class} of the {@code AccessibilityCheck} to get results for * @return a list of {@code AccessibilityCheckResult}s obtained from the given * {@code AccessibilityCheck}. */ public static <T extends AccessibilityCheckResult> List<T> getResultsForCheck( Iterable<T> results, Class<? extends AccessibilityCheck> checkClass) { return getResultsForCheck(results, checkClass, /* aliases= */ null); } /** * Takes a list of {@code AccessibilityCheckResult}s and returns a list with only results obtained * from the given {@code AccessibilityCheck}. If a BiMap of class aliases is provided, the * returned value will also include results obtained from the check class paired with the given * class in the BiMap. */ static <T extends AccessibilityCheckResult> List<T> getResultsForCheck( Iterable<T> results, Class<? extends AccessibilityCheck> checkClass, @Nullable ImmutableBiMap<?, ?> aliases) { List<T> resultsForCheck = new ArrayList<T>(); for (T result : results) { Class<? extends AccessibilityCheck> resultCheckClass = result.getSourceCheckClass(); Object alias = getAlias(resultCheckClass, aliases); if (checkClass.equals(resultCheckClass) || checkClass.equals(alias)) { resultsForCheck.add(result); } } return resultsForCheck; } /** * Filters {@link AccessibilityCheckResult}s and returns a list with only results which match the * given {@link AccessibilityCheckResultType}. * * @param results an {@link Iterable} of {@link AccessibilityCheckResult}s * @param type the {@link AccessibilityCheckResultType} for the results to be returned * @return a list of {@link AccessibilityCheckResult}s with the given * {@link AccessibilityCheckResultType}. */ public static <T extends AccessibilityCheckResult> List<T> getResultsForType(
// Path: src/main/java/com/google/android/apps/common/testing/accessibility/framework/AccessibilityCheckResult.java // public enum AccessibilityCheckResultType { // /** Clearly an accessibility bug, for example no speakable text on a clicked button */ // ERROR(ResultTypeProto.ERROR), // /** // * Potentially an accessibility bug, for example finding another view with the same speakable // * text as a clicked view // */ // WARNING(ResultTypeProto.WARNING), // /** // * Information that may be helpful when evaluating accessibility, for example a listing of all // * speakable text in a view hierarchy in the traversal order used by an accessibility service. // */ // INFO(ResultTypeProto.INFO), // /** // * Indication that a potential issue was identified, but it was resolved as not an accessibility // * problem. // */ // RESOLVED(ResultTypeProto.RESOLVED), // /** A signal that the check was not run at all (ex. because the API level was too low) */ // NOT_RUN(ResultTypeProto.NOT_RUN), // /** // * A result that has been explicitly suppressed from throwing any Exceptions, used to allow for // * known issues. // */ // SUPPRESSED(ResultTypeProto.SUPPRESSED); // // private static final Map<Integer, AccessibilityCheckResultType> PROTO_NUMBER_MAP = // new HashMap<>(); // // static { // for (AccessibilityCheckResultType type : values()) { // PROTO_NUMBER_MAP.put(type.protoNumber, type); // } // } // // final int protoNumber; // // private AccessibilityCheckResultType(ResultTypeProto proto) { // this.protoNumber = proto.getNumber(); // } // // public static AccessibilityCheckResultType fromProto(ResultTypeProto proto) { // AccessibilityCheckResultType type = PROTO_NUMBER_MAP.get(proto.getNumber()); // checkArgument( // (type != null), // "Failed to create AccessibilityCheckResultType from proto with unknown value: %s", // proto.getNumber()); // return checkNotNull(type); // } // // public ResultTypeProto toProto() { // return ResultTypeProto.forNumber(protoNumber); // } // } // Path: src/main/java/com/google/android/apps/common/testing/accessibility/framework/AccessibilityCheckResultBaseUtils.java import com.google.android.apps.common.testing.accessibility.framework.AccessibilityCheckResult.AccessibilityCheckResultType; import com.google.common.collect.ImmutableBiMap; import java.util.ArrayList; import java.util.List; import java.util.Set; import org.checkerframework.checker.nullness.qual.Nullable; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.Matchers; import org.hamcrest.TypeSafeMatcher; /* * Copyright (C) 2014 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.common.testing.accessibility.framework; /** * Utility class for dealing with {@code AccessibilityCheckResult}s, without any dependency upon * Android classes. * * <p>This duplicates some of the methods in {@code AccessibilityCheckResultUtils} in order to * support separate Android and Java build targets while maintaining API compatibility. */ public final class AccessibilityCheckResultBaseUtils { private AccessibilityCheckResultBaseUtils() {} /** * Takes a list of {@code AccessibilityCheckResult}s and returns a list with only results obtained * from the given {@code AccessibilityCheck}. * <p> * NOTE: This method explicitly does not take subtypes of {@code checkClass} into account when * filtering results. * * @param results a list of {@code AccessibilityCheckResult}s * @param checkClass the {@code Class} of the {@code AccessibilityCheck} to get results for * @return a list of {@code AccessibilityCheckResult}s obtained from the given * {@code AccessibilityCheck}. */ public static <T extends AccessibilityCheckResult> List<T> getResultsForCheck( Iterable<T> results, Class<? extends AccessibilityCheck> checkClass) { return getResultsForCheck(results, checkClass, /* aliases= */ null); } /** * Takes a list of {@code AccessibilityCheckResult}s and returns a list with only results obtained * from the given {@code AccessibilityCheck}. If a BiMap of class aliases is provided, the * returned value will also include results obtained from the check class paired with the given * class in the BiMap. */ static <T extends AccessibilityCheckResult> List<T> getResultsForCheck( Iterable<T> results, Class<? extends AccessibilityCheck> checkClass, @Nullable ImmutableBiMap<?, ?> aliases) { List<T> resultsForCheck = new ArrayList<T>(); for (T result : results) { Class<? extends AccessibilityCheck> resultCheckClass = result.getSourceCheckClass(); Object alias = getAlias(resultCheckClass, aliases); if (checkClass.equals(resultCheckClass) || checkClass.equals(alias)) { resultsForCheck.add(result); } } return resultsForCheck; } /** * Filters {@link AccessibilityCheckResult}s and returns a list with only results which match the * given {@link AccessibilityCheckResultType}. * * @param results an {@link Iterable} of {@link AccessibilityCheckResult}s * @param type the {@link AccessibilityCheckResultType} for the results to be returned * @return a list of {@link AccessibilityCheckResult}s with the given * {@link AccessibilityCheckResultType}. */ public static <T extends AccessibilityCheckResult> List<T> getResultsForType(
Iterable<T> results, AccessibilityCheckResultType type) {
google/Accessibility-Test-Framework-for-Android
src/main/java/com/google/android/apps/common/testing/accessibility/framework/integrations/AccessibilityViewCheckException.java
// Path: src/main/java/com/google/android/apps/common/testing/accessibility/framework/AccessibilityViewCheckResult.java // @Deprecated // public class AccessibilityViewCheckResult extends AccessibilityCheckResult { // // private final @Nullable View view; // private final @Nullable Image viewImage; // private final @Nullable AccessibilityHierarchyCheckResult hierarchyCheckResult; // // /** // * @param checkClass The check that generated the error // * @param type The type of the result // * @param message A human-readable message explaining the error // * @param view The view that was responsible for generating the error. This may be {@code null} if // * the result does not apply to a specific {@code View}. // * @param viewImage An image of the {@code View} associated with this finding. This will usually // * be {@code null} except when debugging contrast checks. See {@link // * Parameters#setSaveViewImages(boolean)}. // */ // public AccessibilityViewCheckResult( // Class<? extends AccessibilityCheck> checkClass, // AccessibilityCheckResultType type, // CharSequence message, // @Nullable View view, // @Nullable Image viewImage) { // super(checkClass, type, message); // this.view = view; // this.viewImage = viewImage; // hierarchyCheckResult = null; // } // // /** Constructor without viewImage. */ // public AccessibilityViewCheckResult( // Class<? extends AccessibilityCheck> checkClass, // AccessibilityCheckResultType type, // CharSequence message, // @Nullable View view) { // this(checkClass, type, message, view, /* viewImage= */ null); // } // // /** // * Constructor that takes an AccessibilityHierarchyCheckResult. // * // * @param checkClass The check that generated the error. This should be a ViewCheck // */ // /* package */ AccessibilityViewCheckResult( // Class<? extends AccessibilityCheck> checkClass, // AccessibilityHierarchyCheckResult hierarchyCheckResult, // @Nullable View view) { // super(checkClass, hierarchyCheckResult.getType(), /* message= */ null); // this.view = view; // viewImage = // (hierarchyCheckResult instanceof AccessibilityHierarchyCheckResultWithImage) // ? ((AccessibilityHierarchyCheckResultWithImage) hierarchyCheckResult).getViewImage() // : null; // this.hierarchyCheckResult = hierarchyCheckResult; // } // // /** // * Returns a copy of this result, but with the AccessibilityCheckResultType changed to SUPPRESSED. // */ // public AccessibilityViewCheckResult getSuppressedResultCopy() { // if (hierarchyCheckResult == null) { // return new AccessibilityViewCheckResult( // getSourceCheckClass(), // AccessibilityCheckResultType.SUPPRESSED, // getMessage(Locale.ENGLISH), // getView()); // } else { // return new AccessibilityViewCheckResult( // getSourceCheckClass(), hierarchyCheckResult.getSuppressedResultCopy(), getView()); // } // } // // /** // * Returns the view to which the result applies, or {@code null} if the result does not apply to a // * specific {@code View}. // */ // public @Nullable View getView() { // return view; // } // // /** Returns an image of the view to which the result applies, in some cases, or {@code null}. */ // public @Nullable Image getViewImage() { // return viewImage; // } // // /** // * Returns the type of AccessibilityHierarchyCheck that detected this result. // * // * @throws NullPointerException if this result was not constructed with an // * AccessibilityHierarchyCheckResult // */ // public Class<? extends AccessibilityHierarchyCheck> getAccessibilityHierarchyCheck() { // return checkNotNull(hierarchyCheckResult) // .getSourceCheckClass() // .asSubclass(AccessibilityHierarchyCheck.class); // } // // /** // * Returns the integer id of this result. // * // * @see AccessibilityHierarchyCheckResult#getResultId() // * @throws NullPointerException if this result was not constructed with an // * AccessibilityHierarchyCheckResult // */ // public int getResultId() { // return checkNotNull(hierarchyCheckResult).getResultId(); // } // // /** // * Retrieve the metadata stored in this result. // * // * @see AccessibilityHierarchyCheckResult#getMetadata() // * @throws NullPointerException if this result was not constructed with an // * AccessibilityHierarchyCheckResult // */ // @Pure // public @Nullable ResultMetadata getMetadata() { // return checkNotNull(hierarchyCheckResult).getMetadata(); // } // // @Override // public CharSequence getMessage() { // return (hierarchyCheckResult == null) ? super.getMessage() : hierarchyCheckResult.getMessage(); // } // // @Override // public CharSequence getMessage(Locale locale) { // return (hierarchyCheckResult == null) // ? super.getMessage(locale) // : hierarchyCheckResult.getMessage(locale); // } // }
import com.google.android.apps.common.testing.accessibility.framework.AccessibilityViewCheckResult; import java.util.List;
/* * Copyright (C) 2015 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.common.testing.accessibility.framework.integrations; /** * An exception class to be used for throwing exceptions with accessibility results. * * @deprecated Use the AccessibilityViewCheckException in the espresso sub-package. */ @Deprecated public abstract class AccessibilityViewCheckException extends RuntimeException {
// Path: src/main/java/com/google/android/apps/common/testing/accessibility/framework/AccessibilityViewCheckResult.java // @Deprecated // public class AccessibilityViewCheckResult extends AccessibilityCheckResult { // // private final @Nullable View view; // private final @Nullable Image viewImage; // private final @Nullable AccessibilityHierarchyCheckResult hierarchyCheckResult; // // /** // * @param checkClass The check that generated the error // * @param type The type of the result // * @param message A human-readable message explaining the error // * @param view The view that was responsible for generating the error. This may be {@code null} if // * the result does not apply to a specific {@code View}. // * @param viewImage An image of the {@code View} associated with this finding. This will usually // * be {@code null} except when debugging contrast checks. See {@link // * Parameters#setSaveViewImages(boolean)}. // */ // public AccessibilityViewCheckResult( // Class<? extends AccessibilityCheck> checkClass, // AccessibilityCheckResultType type, // CharSequence message, // @Nullable View view, // @Nullable Image viewImage) { // super(checkClass, type, message); // this.view = view; // this.viewImage = viewImage; // hierarchyCheckResult = null; // } // // /** Constructor without viewImage. */ // public AccessibilityViewCheckResult( // Class<? extends AccessibilityCheck> checkClass, // AccessibilityCheckResultType type, // CharSequence message, // @Nullable View view) { // this(checkClass, type, message, view, /* viewImage= */ null); // } // // /** // * Constructor that takes an AccessibilityHierarchyCheckResult. // * // * @param checkClass The check that generated the error. This should be a ViewCheck // */ // /* package */ AccessibilityViewCheckResult( // Class<? extends AccessibilityCheck> checkClass, // AccessibilityHierarchyCheckResult hierarchyCheckResult, // @Nullable View view) { // super(checkClass, hierarchyCheckResult.getType(), /* message= */ null); // this.view = view; // viewImage = // (hierarchyCheckResult instanceof AccessibilityHierarchyCheckResultWithImage) // ? ((AccessibilityHierarchyCheckResultWithImage) hierarchyCheckResult).getViewImage() // : null; // this.hierarchyCheckResult = hierarchyCheckResult; // } // // /** // * Returns a copy of this result, but with the AccessibilityCheckResultType changed to SUPPRESSED. // */ // public AccessibilityViewCheckResult getSuppressedResultCopy() { // if (hierarchyCheckResult == null) { // return new AccessibilityViewCheckResult( // getSourceCheckClass(), // AccessibilityCheckResultType.SUPPRESSED, // getMessage(Locale.ENGLISH), // getView()); // } else { // return new AccessibilityViewCheckResult( // getSourceCheckClass(), hierarchyCheckResult.getSuppressedResultCopy(), getView()); // } // } // // /** // * Returns the view to which the result applies, or {@code null} if the result does not apply to a // * specific {@code View}. // */ // public @Nullable View getView() { // return view; // } // // /** Returns an image of the view to which the result applies, in some cases, or {@code null}. */ // public @Nullable Image getViewImage() { // return viewImage; // } // // /** // * Returns the type of AccessibilityHierarchyCheck that detected this result. // * // * @throws NullPointerException if this result was not constructed with an // * AccessibilityHierarchyCheckResult // */ // public Class<? extends AccessibilityHierarchyCheck> getAccessibilityHierarchyCheck() { // return checkNotNull(hierarchyCheckResult) // .getSourceCheckClass() // .asSubclass(AccessibilityHierarchyCheck.class); // } // // /** // * Returns the integer id of this result. // * // * @see AccessibilityHierarchyCheckResult#getResultId() // * @throws NullPointerException if this result was not constructed with an // * AccessibilityHierarchyCheckResult // */ // public int getResultId() { // return checkNotNull(hierarchyCheckResult).getResultId(); // } // // /** // * Retrieve the metadata stored in this result. // * // * @see AccessibilityHierarchyCheckResult#getMetadata() // * @throws NullPointerException if this result was not constructed with an // * AccessibilityHierarchyCheckResult // */ // @Pure // public @Nullable ResultMetadata getMetadata() { // return checkNotNull(hierarchyCheckResult).getMetadata(); // } // // @Override // public CharSequence getMessage() { // return (hierarchyCheckResult == null) ? super.getMessage() : hierarchyCheckResult.getMessage(); // } // // @Override // public CharSequence getMessage(Locale locale) { // return (hierarchyCheckResult == null) // ? super.getMessage(locale) // : hierarchyCheckResult.getMessage(locale); // } // } // Path: src/main/java/com/google/android/apps/common/testing/accessibility/framework/integrations/AccessibilityViewCheckException.java import com.google.android.apps.common.testing.accessibility.framework.AccessibilityViewCheckResult; import java.util.List; /* * Copyright (C) 2015 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.common.testing.accessibility.framework.integrations; /** * An exception class to be used for throwing exceptions with accessibility results. * * @deprecated Use the AccessibilityViewCheckException in the espresso sub-package. */ @Deprecated public abstract class AccessibilityViewCheckException extends RuntimeException {
private final List<AccessibilityViewCheckResult> results;
google/Accessibility-Test-Framework-for-Android
src/main/java/com/google/android/apps/common/testing/accessibility/framework/uielement/ViewHierarchyAction.java
// Path: src/main/java/com/google/android/apps/common/testing/accessibility/framework/replacements/TextUtils.java // public class TextUtils { // private TextUtils() { // // Not instantiable // } // // /** // * @see android.text.TextUtils#isEmpty(CharSequence) // */ // @EnsuresNonNullIf(expression = "#1", result = false) // public static boolean isEmpty(@Nullable CharSequence str) { // return (str == null) || (str.length() == 0); // } // // /** See {@link android.text.TextUtils#getTrimmedLength(CharSequence)}. */ // public static int getTrimmedLength(CharSequence str) { // return str.toString().trim().length(); // } // // /** See {@link android.text.TextUtils#equals(CharSequence, CharSequence)}. */ // public static boolean equals(@Nullable CharSequence s1, @Nullable CharSequence s2) { // if (s1 == s2) { // return true; // } // // if ((s1 != null) && (s2 != null) && (s1.length() == s2.length())) { // if (s1 instanceof String && s2 instanceof String) { // return ((String) s1).equals((String) s2); // } else { // for (int i = 0; i < s1.length(); i++) { // if (s1.charAt(i) != s2.charAt(i)) { // return false; // } // } // return true; // } // } // return false; // } // }
import com.google.android.apps.common.testing.accessibility.framework.replacements.TextUtils; import com.google.android.apps.common.testing.accessibility.framework.uielement.proto.AccessibilityHierarchyProtos.ViewHierarchyActionProto; import org.checkerframework.checker.nullness.qual.Nullable;
package com.google.android.apps.common.testing.accessibility.framework.uielement; /** * Representation of {@code AccessibilityNodeInfo.AccessibilityAction} in a {@code View}. * * <p>The action exists within {@code ViewHierarchyElement} and it is one-to-one map from {@code * AccessibilityAction}. */ public class ViewHierarchyAction { private final int actionId; private final @Nullable CharSequence actionLabel; protected ViewHierarchyAction(int actionId, @Nullable CharSequence actionLabel) { this.actionId = actionId; this.actionLabel = actionLabel; } ViewHierarchyAction(ViewHierarchyActionProto proto) { this.actionId = proto.getActionId(); this.actionLabel = proto.hasActionLabel() ? proto.getActionLabel() : null; } /** * Returns the action Id. Action Id will be one of the actions that are listed in {@code * AccessibilityNodeInfo}. */ int getActionId() { return actionId; } /** Returns the label of the corresponding action id. */ @Nullable CharSequence getActionLabel() { return actionLabel; } ViewHierarchyActionProto toProto() { ViewHierarchyActionProto.Builder builder = ViewHierarchyActionProto.newBuilder(); builder.setActionId(actionId);
// Path: src/main/java/com/google/android/apps/common/testing/accessibility/framework/replacements/TextUtils.java // public class TextUtils { // private TextUtils() { // // Not instantiable // } // // /** // * @see android.text.TextUtils#isEmpty(CharSequence) // */ // @EnsuresNonNullIf(expression = "#1", result = false) // public static boolean isEmpty(@Nullable CharSequence str) { // return (str == null) || (str.length() == 0); // } // // /** See {@link android.text.TextUtils#getTrimmedLength(CharSequence)}. */ // public static int getTrimmedLength(CharSequence str) { // return str.toString().trim().length(); // } // // /** See {@link android.text.TextUtils#equals(CharSequence, CharSequence)}. */ // public static boolean equals(@Nullable CharSequence s1, @Nullable CharSequence s2) { // if (s1 == s2) { // return true; // } // // if ((s1 != null) && (s2 != null) && (s1.length() == s2.length())) { // if (s1 instanceof String && s2 instanceof String) { // return ((String) s1).equals((String) s2); // } else { // for (int i = 0; i < s1.length(); i++) { // if (s1.charAt(i) != s2.charAt(i)) { // return false; // } // } // return true; // } // } // return false; // } // } // Path: src/main/java/com/google/android/apps/common/testing/accessibility/framework/uielement/ViewHierarchyAction.java import com.google.android.apps.common.testing.accessibility.framework.replacements.TextUtils; import com.google.android.apps.common.testing.accessibility.framework.uielement.proto.AccessibilityHierarchyProtos.ViewHierarchyActionProto; import org.checkerframework.checker.nullness.qual.Nullable; package com.google.android.apps.common.testing.accessibility.framework.uielement; /** * Representation of {@code AccessibilityNodeInfo.AccessibilityAction} in a {@code View}. * * <p>The action exists within {@code ViewHierarchyElement} and it is one-to-one map from {@code * AccessibilityAction}. */ public class ViewHierarchyAction { private final int actionId; private final @Nullable CharSequence actionLabel; protected ViewHierarchyAction(int actionId, @Nullable CharSequence actionLabel) { this.actionId = actionId; this.actionLabel = actionLabel; } ViewHierarchyAction(ViewHierarchyActionProto proto) { this.actionId = proto.getActionId(); this.actionLabel = proto.hasActionLabel() ? proto.getActionLabel() : null; } /** * Returns the action Id. Action Id will be one of the actions that are listed in {@code * AccessibilityNodeInfo}. */ int getActionId() { return actionId; } /** Returns the label of the corresponding action id. */ @Nullable CharSequence getActionLabel() { return actionLabel; } ViewHierarchyActionProto toProto() { ViewHierarchyActionProto.Builder builder = ViewHierarchyActionProto.newBuilder(); builder.setActionId(actionId);
if (!TextUtils.isEmpty(actionLabel)) {
google/Accessibility-Test-Framework-for-Android
src/main/java/com/google/android/apps/common/testing/accessibility/framework/SpeakableTextPresentViewCheck.java
// Path: src/main/java/com/google/android/apps/common/testing/accessibility/framework/checks/SpeakableTextPresentCheck.java // public class SpeakableTextPresentCheck extends AccessibilityHierarchyCheck { // // /** Result when thew view is not visible. */ // public static final int RESULT_ID_NOT_VISIBLE = 1; // /** Result when the view is not {@code importantForAccessibility}. */ // public static final int RESULT_ID_NOT_IMPORTANT_FOR_ACCESSIBILITY = 2; // /** Result when the view should not be focused by a screen reader. */ // public static final int RESULT_ID_SHOULD_NOT_FOCUS = 3; // /** Result when the view is missing speakable text. */ // public static final int RESULT_ID_MISSING_SPEAKABLE_TEXT = 4; // /** Result when the view type is excluded. */ // public static final int RESULT_ID_WEB_CONTENT = 5; // // @Override // protected String getHelpTopic() { // return "7158690"; // Content labels // } // // @Override // public Category getCategory() { // return Category.CONTENT_LABELING; // } // // @Override // public List<AccessibilityHierarchyCheckResult> runCheckOnHierarchy( // AccessibilityHierarchy hierarchy, // @Nullable ViewHierarchyElement fromRoot, // @Nullable Parameters parameters) { // List<AccessibilityHierarchyCheckResult> results = new ArrayList<>(); // List<? extends ViewHierarchyElement> viewsToEval = getElementsToEvaluate(fromRoot, hierarchy); // for (ViewHierarchyElement element : viewsToEval) { // if (!TRUE.equals(element.isVisibleToUser())) { // results.add(new AccessibilityHierarchyCheckResult( // this.getClass(), // AccessibilityCheckResultType.NOT_RUN, // element, // RESULT_ID_NOT_VISIBLE, // null)); // continue; // } // // if (!element.isImportantForAccessibility()) { // results.add(new AccessibilityHierarchyCheckResult( // this.getClass(), // AccessibilityCheckResultType.NOT_RUN, // element, // RESULT_ID_NOT_IMPORTANT_FOR_ACCESSIBILITY, // null)); // continue; // } // // if (element.checkInstanceOf(ViewHierarchyElementUtils.WEB_VIEW_CLASS_NAME) // && element.getChildViewCount() == 0) { // results.add(new AccessibilityHierarchyCheckResult( // this.getClass(), // AccessibilityCheckResultType.NOT_RUN, // element, // RESULT_ID_WEB_CONTENT, // null)); // continue; // } // // if (!ViewHierarchyElementUtils.shouldFocusView(element)) { // results.add(new AccessibilityHierarchyCheckResult( // this.getClass(), // AccessibilityCheckResultType.NOT_RUN, // element, // RESULT_ID_SHOULD_NOT_FOCUS, // null)); // continue; // } // // if (TextUtils.isEmpty(ViewHierarchyElementUtils.getSpeakableTextForElement(element))) { // results.add(new AccessibilityHierarchyCheckResult( // this.getClass(), // AccessibilityCheckResultType.ERROR, // element, // RESULT_ID_MISSING_SPEAKABLE_TEXT, // null)); // } // } // return results; // } // // @Override // public String getMessageForResultData( // Locale locale, int resultId, @Nullable ResultMetadata metadata) { // return generateMessageForResultId(locale, resultId); // } // // @Override // public String getShortMessageForResultData( // Locale locale, int resultId, @Nullable ResultMetadata metadata) { // return generateMessageForResultId(locale, resultId); // } // // @Override // public String getTitleMessage(Locale locale) { // return StringManager.getString(locale, "check_title_speakable_text_present"); // } // // private static String generateMessageForResultId(Locale locale, int resultId) { // switch(resultId) { // case RESULT_ID_NOT_VISIBLE: // return StringManager.getString(locale, "result_message_not_visible"); // case RESULT_ID_NOT_IMPORTANT_FOR_ACCESSIBILITY: // return StringManager.getString(locale, "result_message_not_important_for_accessibility"); // case RESULT_ID_SHOULD_NOT_FOCUS: // return StringManager.getString(locale, "result_message_should_not_focus"); // case RESULT_ID_MISSING_SPEAKABLE_TEXT: // return StringManager.getString(locale, "result_message_missing_speakable_text"); // case RESULT_ID_WEB_CONTENT: // return StringManager.getString(locale, "result_message_web_content"); // default: // throw new IllegalStateException("Unsupported result id"); // } // } // }
import android.view.View; import com.google.android.apps.common.testing.accessibility.framework.checks.SpeakableTextPresentCheck; import java.util.List; import org.checkerframework.checker.nullness.qual.Nullable;
/* * Copyright (C) 2014 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.common.testing.accessibility.framework; /** * Check to ensure that a view has a content description for a screen reader * * @deprecated Replaced by {@link SpeakableTextPresentCheck} */ @Deprecated public class SpeakableTextPresentViewCheck extends AccessibilityViewHierarchyCheck {
// Path: src/main/java/com/google/android/apps/common/testing/accessibility/framework/checks/SpeakableTextPresentCheck.java // public class SpeakableTextPresentCheck extends AccessibilityHierarchyCheck { // // /** Result when thew view is not visible. */ // public static final int RESULT_ID_NOT_VISIBLE = 1; // /** Result when the view is not {@code importantForAccessibility}. */ // public static final int RESULT_ID_NOT_IMPORTANT_FOR_ACCESSIBILITY = 2; // /** Result when the view should not be focused by a screen reader. */ // public static final int RESULT_ID_SHOULD_NOT_FOCUS = 3; // /** Result when the view is missing speakable text. */ // public static final int RESULT_ID_MISSING_SPEAKABLE_TEXT = 4; // /** Result when the view type is excluded. */ // public static final int RESULT_ID_WEB_CONTENT = 5; // // @Override // protected String getHelpTopic() { // return "7158690"; // Content labels // } // // @Override // public Category getCategory() { // return Category.CONTENT_LABELING; // } // // @Override // public List<AccessibilityHierarchyCheckResult> runCheckOnHierarchy( // AccessibilityHierarchy hierarchy, // @Nullable ViewHierarchyElement fromRoot, // @Nullable Parameters parameters) { // List<AccessibilityHierarchyCheckResult> results = new ArrayList<>(); // List<? extends ViewHierarchyElement> viewsToEval = getElementsToEvaluate(fromRoot, hierarchy); // for (ViewHierarchyElement element : viewsToEval) { // if (!TRUE.equals(element.isVisibleToUser())) { // results.add(new AccessibilityHierarchyCheckResult( // this.getClass(), // AccessibilityCheckResultType.NOT_RUN, // element, // RESULT_ID_NOT_VISIBLE, // null)); // continue; // } // // if (!element.isImportantForAccessibility()) { // results.add(new AccessibilityHierarchyCheckResult( // this.getClass(), // AccessibilityCheckResultType.NOT_RUN, // element, // RESULT_ID_NOT_IMPORTANT_FOR_ACCESSIBILITY, // null)); // continue; // } // // if (element.checkInstanceOf(ViewHierarchyElementUtils.WEB_VIEW_CLASS_NAME) // && element.getChildViewCount() == 0) { // results.add(new AccessibilityHierarchyCheckResult( // this.getClass(), // AccessibilityCheckResultType.NOT_RUN, // element, // RESULT_ID_WEB_CONTENT, // null)); // continue; // } // // if (!ViewHierarchyElementUtils.shouldFocusView(element)) { // results.add(new AccessibilityHierarchyCheckResult( // this.getClass(), // AccessibilityCheckResultType.NOT_RUN, // element, // RESULT_ID_SHOULD_NOT_FOCUS, // null)); // continue; // } // // if (TextUtils.isEmpty(ViewHierarchyElementUtils.getSpeakableTextForElement(element))) { // results.add(new AccessibilityHierarchyCheckResult( // this.getClass(), // AccessibilityCheckResultType.ERROR, // element, // RESULT_ID_MISSING_SPEAKABLE_TEXT, // null)); // } // } // return results; // } // // @Override // public String getMessageForResultData( // Locale locale, int resultId, @Nullable ResultMetadata metadata) { // return generateMessageForResultId(locale, resultId); // } // // @Override // public String getShortMessageForResultData( // Locale locale, int resultId, @Nullable ResultMetadata metadata) { // return generateMessageForResultId(locale, resultId); // } // // @Override // public String getTitleMessage(Locale locale) { // return StringManager.getString(locale, "check_title_speakable_text_present"); // } // // private static String generateMessageForResultId(Locale locale, int resultId) { // switch(resultId) { // case RESULT_ID_NOT_VISIBLE: // return StringManager.getString(locale, "result_message_not_visible"); // case RESULT_ID_NOT_IMPORTANT_FOR_ACCESSIBILITY: // return StringManager.getString(locale, "result_message_not_important_for_accessibility"); // case RESULT_ID_SHOULD_NOT_FOCUS: // return StringManager.getString(locale, "result_message_should_not_focus"); // case RESULT_ID_MISSING_SPEAKABLE_TEXT: // return StringManager.getString(locale, "result_message_missing_speakable_text"); // case RESULT_ID_WEB_CONTENT: // return StringManager.getString(locale, "result_message_web_content"); // default: // throw new IllegalStateException("Unsupported result id"); // } // } // } // Path: src/main/java/com/google/android/apps/common/testing/accessibility/framework/SpeakableTextPresentViewCheck.java import android.view.View; import com.google.android.apps.common.testing.accessibility.framework.checks.SpeakableTextPresentCheck; import java.util.List; import org.checkerframework.checker.nullness.qual.Nullable; /* * Copyright (C) 2014 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.common.testing.accessibility.framework; /** * Check to ensure that a view has a content description for a screen reader * * @deprecated Replaced by {@link SpeakableTextPresentCheck} */ @Deprecated public class SpeakableTextPresentViewCheck extends AccessibilityViewHierarchyCheck {
private static final SpeakableTextPresentCheck DELEGATION_CHECK = new SpeakableTextPresentCheck();
google/Accessibility-Test-Framework-for-Android
src/main/java/com/google/android/apps/common/testing/accessibility/framework/EditableContentDescViewCheck.java
// Path: src/main/java/com/google/android/apps/common/testing/accessibility/framework/checks/EditableContentDescCheck.java // public class EditableContentDescCheck extends AccessibilityHierarchyCheck { // // /** Result when thew view is not {@code importantForAccessibility} */ // public static final int RESULT_ID_NOT_IMPORTANT_FOR_ACCESSIBILITY = 1; // /** Result when the view is an editable {@link TextView} with a {@code contentDescription}. */ // public static final int RESULT_ID_EDITABLE_TEXTVIEW_CONTENT_DESC = 2; // /** Result when the view is not an editable {@link TextView}. */ // public static final int RESULT_ID_NOT_EDITABLE_TEXTVIEW = 3; // // @Override // protected String getHelpTopic() { // return "6378120"; // Editable View labels // } // // @Override // public Category getCategory() { // return Category.IMPLEMENTATION; // } // // @Override // public List<AccessibilityHierarchyCheckResult> runCheckOnHierarchy( // AccessibilityHierarchy hierarchy, // @Nullable ViewHierarchyElement fromRoot, // @Nullable Parameters parameters) { // List<AccessibilityHierarchyCheckResult> results = new ArrayList<>(); // List<? extends ViewHierarchyElement> viewsToEval = getElementsToEvaluate(fromRoot, hierarchy); // for (ViewHierarchyElement view : viewsToEval) { // if (!view.isImportantForAccessibility()) { // results.add(new AccessibilityHierarchyCheckResult( // this.getClass(), // AccessibilityCheckResultType.NOT_RUN, // view, // RESULT_ID_NOT_IMPORTANT_FOR_ACCESSIBILITY, // null)); // continue; // } // // if (TRUE.equals(view.isEditable()) // || view.checkInstanceOf(ViewHierarchyElementUtils.EDIT_TEXT_CLASS_NAME)) { // if (!TextUtils.isEmpty(view.getContentDescription())) { // results.add(new AccessibilityHierarchyCheckResult(this.getClass(), // AccessibilityCheckResultType.ERROR, // view, // RESULT_ID_EDITABLE_TEXTVIEW_CONTENT_DESC, // null)); // } // } else { // results.add(new AccessibilityHierarchyCheckResult(this.getClass(), // AccessibilityCheckResultType.NOT_RUN, // view, // RESULT_ID_NOT_EDITABLE_TEXTVIEW, // null)); // } // } // // return results; // } // // @Override // public String getMessageForResultData( // Locale locale, int resultId, @Nullable ResultMetadata metadata) { // return generateMessageForResultId(locale, resultId); // } // // @Override // public String getShortMessageForResultData( // Locale locale, int resultId, @Nullable ResultMetadata metadata) { // return generateMessageForResultId(locale, resultId); // } // // @Override // public String getTitleMessage(Locale locale) { // return StringManager.getString(locale, "check_title_editable_content_desc"); // } // // private static String generateMessageForResultId(Locale locale, int resultId) { // switch(resultId) { // case RESULT_ID_NOT_IMPORTANT_FOR_ACCESSIBILITY: // return StringManager.getString(locale, "result_message_not_important_for_accessibility"); // case RESULT_ID_EDITABLE_TEXTVIEW_CONTENT_DESC: // return StringManager.getString(locale, "result_message_editable_textview_content_desc"); // case RESULT_ID_NOT_EDITABLE_TEXTVIEW: // return StringManager.getString(locale, "result_message_not_editable_textview"); // default: // throw new IllegalStateException("Unsupported result id"); // } // } // }
import android.view.View; import com.google.android.apps.common.testing.accessibility.framework.checks.EditableContentDescCheck; import java.util.List; import org.checkerframework.checker.nullness.qual.Nullable;
/* * Copyright (C) 2014 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.common.testing.accessibility.framework; /** * Check to ensure that an editable TextView is not labeled by a contentDescription * * @deprecated Replaced by {@link EditableContentDescCheck} */ @Deprecated public class EditableContentDescViewCheck extends AccessibilityViewHierarchyCheck {
// Path: src/main/java/com/google/android/apps/common/testing/accessibility/framework/checks/EditableContentDescCheck.java // public class EditableContentDescCheck extends AccessibilityHierarchyCheck { // // /** Result when thew view is not {@code importantForAccessibility} */ // public static final int RESULT_ID_NOT_IMPORTANT_FOR_ACCESSIBILITY = 1; // /** Result when the view is an editable {@link TextView} with a {@code contentDescription}. */ // public static final int RESULT_ID_EDITABLE_TEXTVIEW_CONTENT_DESC = 2; // /** Result when the view is not an editable {@link TextView}. */ // public static final int RESULT_ID_NOT_EDITABLE_TEXTVIEW = 3; // // @Override // protected String getHelpTopic() { // return "6378120"; // Editable View labels // } // // @Override // public Category getCategory() { // return Category.IMPLEMENTATION; // } // // @Override // public List<AccessibilityHierarchyCheckResult> runCheckOnHierarchy( // AccessibilityHierarchy hierarchy, // @Nullable ViewHierarchyElement fromRoot, // @Nullable Parameters parameters) { // List<AccessibilityHierarchyCheckResult> results = new ArrayList<>(); // List<? extends ViewHierarchyElement> viewsToEval = getElementsToEvaluate(fromRoot, hierarchy); // for (ViewHierarchyElement view : viewsToEval) { // if (!view.isImportantForAccessibility()) { // results.add(new AccessibilityHierarchyCheckResult( // this.getClass(), // AccessibilityCheckResultType.NOT_RUN, // view, // RESULT_ID_NOT_IMPORTANT_FOR_ACCESSIBILITY, // null)); // continue; // } // // if (TRUE.equals(view.isEditable()) // || view.checkInstanceOf(ViewHierarchyElementUtils.EDIT_TEXT_CLASS_NAME)) { // if (!TextUtils.isEmpty(view.getContentDescription())) { // results.add(new AccessibilityHierarchyCheckResult(this.getClass(), // AccessibilityCheckResultType.ERROR, // view, // RESULT_ID_EDITABLE_TEXTVIEW_CONTENT_DESC, // null)); // } // } else { // results.add(new AccessibilityHierarchyCheckResult(this.getClass(), // AccessibilityCheckResultType.NOT_RUN, // view, // RESULT_ID_NOT_EDITABLE_TEXTVIEW, // null)); // } // } // // return results; // } // // @Override // public String getMessageForResultData( // Locale locale, int resultId, @Nullable ResultMetadata metadata) { // return generateMessageForResultId(locale, resultId); // } // // @Override // public String getShortMessageForResultData( // Locale locale, int resultId, @Nullable ResultMetadata metadata) { // return generateMessageForResultId(locale, resultId); // } // // @Override // public String getTitleMessage(Locale locale) { // return StringManager.getString(locale, "check_title_editable_content_desc"); // } // // private static String generateMessageForResultId(Locale locale, int resultId) { // switch(resultId) { // case RESULT_ID_NOT_IMPORTANT_FOR_ACCESSIBILITY: // return StringManager.getString(locale, "result_message_not_important_for_accessibility"); // case RESULT_ID_EDITABLE_TEXTVIEW_CONTENT_DESC: // return StringManager.getString(locale, "result_message_editable_textview_content_desc"); // case RESULT_ID_NOT_EDITABLE_TEXTVIEW: // return StringManager.getString(locale, "result_message_not_editable_textview"); // default: // throw new IllegalStateException("Unsupported result id"); // } // } // } // Path: src/main/java/com/google/android/apps/common/testing/accessibility/framework/EditableContentDescViewCheck.java import android.view.View; import com.google.android.apps.common.testing.accessibility.framework.checks.EditableContentDescCheck; import java.util.List; import org.checkerframework.checker.nullness.qual.Nullable; /* * Copyright (C) 2014 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.common.testing.accessibility.framework; /** * Check to ensure that an editable TextView is not labeled by a contentDescription * * @deprecated Replaced by {@link EditableContentDescCheck} */ @Deprecated public class EditableContentDescViewCheck extends AccessibilityViewHierarchyCheck {
private static final EditableContentDescCheck DELEGATION_CHECK = new EditableContentDescCheck();
yurisuzukiltd/AR-Music-Kit
ARMusicKit/app/src/main/java/com/yurisuzuki/ActivityIntro.java
// Path: ARMusicKit/app/src/main/java/com/yurisuzuki/fragment/FragmentIntroBase.java // public class FragmentIntroBase extends Fragment { // // // IntroFragmentAdapter introFragmentAdapter; // ViewPager viewPager; // PageIndicator pageIndicator; // public String type; // // // // /** // * Use this factory method to create a new instance of // * this fragment using the provided parameters. // * // * @param type Parameter 1. // * @return A new instance of fragment FragmentIntroBase. // */ // // TODO: Rename and change types and number of parameters // public static FragmentIntroBase newInstance(String type) { // FragmentIntroBase fragment = new FragmentIntroBase(); // Bundle args = new Bundle(); // args.putString("type", type); // fragment.setArguments(args); // return fragment; // } // // public FragmentIntroBase() { // // Required empty public constructor // } // // @Override // public void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // if (getArguments() != null) { // type = getArguments().getString("type"); // } // } // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, // Bundle savedInstanceState) { // // Inflate the layout for this fragment // View view = inflater.inflate(R.layout.fragment_intro_base, container, false); // // TextView titleView = (TextView)view.findViewById(R.id.inst_title); // if(type != null){ // int title; // if(type.equals("guitar")){ // title = R.string.inst_title_guitar; // }else if(type.equals("piano")){ // title = R.string.inst_title_piano; // }else if(type.equals("musicbox")){ // title = R.string.inst_title_mb; // }else if(type.equals("trace")){ // title = R.string.inst_title_trace; // }else{ // title = R.string.inst_title_trace; // } // titleView.setText(title); // } // // Button startButton = (Button)view.findViewById(R.id.get_started_button); // // startButton.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // viewPager.setCurrentItem(0); // ((ActivityIntro)FragmentIntroBase.this.getActivity()).jumpToCamera(); // } // }); // // return view; // } // // @Override // public void onActivityCreated(Bundle savedInstanceState) { // super.onActivityCreated(savedInstanceState); // // if (savedInstanceState == null) { // viewPager = (ViewPager) getActivity().findViewById(R.id.pager); // pageIndicator = (CirclePageIndicator) getActivity().findViewById( // R.id.indicator); // ((CirclePageIndicator)pageIndicator).setFillColor(0xFF939597); // // // // introFragmentAdapter = new IntroFragmentAdapter(this.getActivity() // .getFragmentManager()); // introFragmentAdapter.type = this.type; // viewPager.setAdapter(introFragmentAdapter); // // pageIndicator.setViewPager(viewPager); // introFragmentAdapter.notifyDataSetChanged(); // // // // } // // } // // // @Override // public void onAttach(Activity activity) { // super.onAttach(activity); // try { // //mListener = (OnFragmentInteractionListener) activity; // } catch (ClassCastException e) { // e.printStackTrace(); // } // } // // @Override // public void onDetach() { // super.onDetach(); // //mListener = null; // } // // // // }
import android.app.Activity; import android.app.Fragment; import android.content.Intent; import android.os.Bundle; import android.view.MenuItem; import com.yurisuzuki.fragment.FragmentIntroBase; import com.yurisuzuki.playsound.R;
/* * Author(s): Takamitsu Mizutori, Goldrush Computing Inc. */ package com.yurisuzuki; ; public class ActivityIntro extends Activity { public static final String TAG = "ActivityIntro"; private String type; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_intro); Bundle extras = getIntent().getExtras(); if (extras != null) { type = extras.getString("type"); } showIntro(); } private void showIntro(){ //ActionBar actionBar = getActionBar(); //actionBar.hide();
// Path: ARMusicKit/app/src/main/java/com/yurisuzuki/fragment/FragmentIntroBase.java // public class FragmentIntroBase extends Fragment { // // // IntroFragmentAdapter introFragmentAdapter; // ViewPager viewPager; // PageIndicator pageIndicator; // public String type; // // // // /** // * Use this factory method to create a new instance of // * this fragment using the provided parameters. // * // * @param type Parameter 1. // * @return A new instance of fragment FragmentIntroBase. // */ // // TODO: Rename and change types and number of parameters // public static FragmentIntroBase newInstance(String type) { // FragmentIntroBase fragment = new FragmentIntroBase(); // Bundle args = new Bundle(); // args.putString("type", type); // fragment.setArguments(args); // return fragment; // } // // public FragmentIntroBase() { // // Required empty public constructor // } // // @Override // public void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // if (getArguments() != null) { // type = getArguments().getString("type"); // } // } // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, // Bundle savedInstanceState) { // // Inflate the layout for this fragment // View view = inflater.inflate(R.layout.fragment_intro_base, container, false); // // TextView titleView = (TextView)view.findViewById(R.id.inst_title); // if(type != null){ // int title; // if(type.equals("guitar")){ // title = R.string.inst_title_guitar; // }else if(type.equals("piano")){ // title = R.string.inst_title_piano; // }else if(type.equals("musicbox")){ // title = R.string.inst_title_mb; // }else if(type.equals("trace")){ // title = R.string.inst_title_trace; // }else{ // title = R.string.inst_title_trace; // } // titleView.setText(title); // } // // Button startButton = (Button)view.findViewById(R.id.get_started_button); // // startButton.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // viewPager.setCurrentItem(0); // ((ActivityIntro)FragmentIntroBase.this.getActivity()).jumpToCamera(); // } // }); // // return view; // } // // @Override // public void onActivityCreated(Bundle savedInstanceState) { // super.onActivityCreated(savedInstanceState); // // if (savedInstanceState == null) { // viewPager = (ViewPager) getActivity().findViewById(R.id.pager); // pageIndicator = (CirclePageIndicator) getActivity().findViewById( // R.id.indicator); // ((CirclePageIndicator)pageIndicator).setFillColor(0xFF939597); // // // // introFragmentAdapter = new IntroFragmentAdapter(this.getActivity() // .getFragmentManager()); // introFragmentAdapter.type = this.type; // viewPager.setAdapter(introFragmentAdapter); // // pageIndicator.setViewPager(viewPager); // introFragmentAdapter.notifyDataSetChanged(); // // // // } // // } // // // @Override // public void onAttach(Activity activity) { // super.onAttach(activity); // try { // //mListener = (OnFragmentInteractionListener) activity; // } catch (ClassCastException e) { // e.printStackTrace(); // } // } // // @Override // public void onDetach() { // super.onDetach(); // //mListener = null; // } // // // // } // Path: ARMusicKit/app/src/main/java/com/yurisuzuki/ActivityIntro.java import android.app.Activity; import android.app.Fragment; import android.content.Intent; import android.os.Bundle; import android.view.MenuItem; import com.yurisuzuki.fragment.FragmentIntroBase; import com.yurisuzuki.playsound.R; /* * Author(s): Takamitsu Mizutori, Goldrush Computing Inc. */ package com.yurisuzuki; ; public class ActivityIntro extends Activity { public static final String TAG = "ActivityIntro"; private String type; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_intro); Bundle extras = getIntent().getExtras(); if (extras != null) { type = extras.getString("type"); } showIntro(); } private void showIntro(){ //ActionBar actionBar = getActionBar(); //actionBar.hide();
Fragment fragment = FragmentIntroBase.newInstance(type);
yurisuzukiltd/AR-Music-Kit
ARMusicKit/app/src/main/java/com/yurisuzuki/fragment/FragmentMenu.java
// Path: ARMusicKit/app/src/main/java/com/yurisuzuki/CustomTypefaceSpan.java // public class CustomTypefaceSpan extends TypefaceSpan { // private final Typeface newType; // // public CustomTypefaceSpan(String family, Typeface type) { // super(family); // newType = type; // } // // @Override // public void updateDrawState(TextPaint ds) { // applyCustomTypeFace(ds, newType); // } // // @Override // public void updateMeasureState(TextPaint paint) { // applyCustomTypeFace(paint, newType); // } // // private static void applyCustomTypeFace(Paint paint, Typeface tf) { // int oldStyle; // Typeface old = paint.getTypeface(); // if (old == null) { // oldStyle = 0; // } else { // oldStyle = old.getStyle(); // } // // int fake = oldStyle & ~tf.getStyle(); // if ((fake & Typeface.BOLD) != 0) { // paint.setFakeBoldText(true); // } // // if ((fake & Typeface.ITALIC) != 0) { // paint.setTextSkewX(-0.25f); // } // // paint.setTypeface(tf); // } // } // // Path: ARMusicKit/app/src/main/java/com/yurisuzuki/MainActivity.java // public class MainActivity extends Activity { // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_main); // // android.app.FragmentManager fm = getFragmentManager(); // FragmentMenu fragment = (FragmentMenu) fm.findFragmentByTag("FragmentMenu"); // if (fragment == null) { // fragment = FragmentMenu.newInstance(); // } // // if(fragment.isAdded() == false){ // fm.beginTransaction() // .add(R.id.main_container, fragment, "FragmentMenu") // .commit(); // } // // } // // public void jumpToCamera(){ // Intent intent = new Intent(this, CameraActivity.class); // startActivity(intent); // //finish(); // //overridePendingTransition(R.anim.fade_in, R.anim.scale_out); // } // // // public void showInstruction(String tag) { // Intent intent = new Intent(this, ActivityIntro.class); // intent.putExtra("type", tag); // startActivity(intent); // //finish(); // //overridePendingTransition(R.anim.fade_in, R.anim.scale_out); // } // // public void showMakeMarkerTop(){ // Intent intent = new Intent(this, ActivityMakeMarkerTop.class); // startActivity(intent); // } // // public void showAbout(){ // Intent intent = new Intent(this, ActivityAbout.class); // startActivity(intent); // } // }
import android.app.Fragment; import android.graphics.Typeface; import android.os.Bundle; import android.text.Spannable; import android.text.SpannableString; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.yurisuzuki.CustomTypefaceSpan; import com.yurisuzuki.MainActivity; import com.yurisuzuki.playsound.R; import java.util.ArrayList;
} public void configureMenus(){ Typeface tfLight = Typeface.createFromAsset(getActivity().getAssets(), "fonts/HelveticaNeueLTStd-Lt.otf"); Typeface tfBold = Typeface.createFromAsset(getActivity().getAssets(), "fonts/HelveticaNeueLTStd-Bd.otf"); for(TextView textView : textViews){ final String text = (String)textView.getText(); String[] list = text.split(" "); String firstWord = list[0]; String secondWord = null; if(list.length > 1){ firstWord += " "; secondWord = list[1]; if(list.length == 3){ secondWord = secondWord + " " + list[2]; } }else{ secondWord = ""; } // Create a new spannable with the two strings Spannable spannable = new SpannableString(firstWord+secondWord); // Set the custom typeface to span over a section of the spannable object
// Path: ARMusicKit/app/src/main/java/com/yurisuzuki/CustomTypefaceSpan.java // public class CustomTypefaceSpan extends TypefaceSpan { // private final Typeface newType; // // public CustomTypefaceSpan(String family, Typeface type) { // super(family); // newType = type; // } // // @Override // public void updateDrawState(TextPaint ds) { // applyCustomTypeFace(ds, newType); // } // // @Override // public void updateMeasureState(TextPaint paint) { // applyCustomTypeFace(paint, newType); // } // // private static void applyCustomTypeFace(Paint paint, Typeface tf) { // int oldStyle; // Typeface old = paint.getTypeface(); // if (old == null) { // oldStyle = 0; // } else { // oldStyle = old.getStyle(); // } // // int fake = oldStyle & ~tf.getStyle(); // if ((fake & Typeface.BOLD) != 0) { // paint.setFakeBoldText(true); // } // // if ((fake & Typeface.ITALIC) != 0) { // paint.setTextSkewX(-0.25f); // } // // paint.setTypeface(tf); // } // } // // Path: ARMusicKit/app/src/main/java/com/yurisuzuki/MainActivity.java // public class MainActivity extends Activity { // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_main); // // android.app.FragmentManager fm = getFragmentManager(); // FragmentMenu fragment = (FragmentMenu) fm.findFragmentByTag("FragmentMenu"); // if (fragment == null) { // fragment = FragmentMenu.newInstance(); // } // // if(fragment.isAdded() == false){ // fm.beginTransaction() // .add(R.id.main_container, fragment, "FragmentMenu") // .commit(); // } // // } // // public void jumpToCamera(){ // Intent intent = new Intent(this, CameraActivity.class); // startActivity(intent); // //finish(); // //overridePendingTransition(R.anim.fade_in, R.anim.scale_out); // } // // // public void showInstruction(String tag) { // Intent intent = new Intent(this, ActivityIntro.class); // intent.putExtra("type", tag); // startActivity(intent); // //finish(); // //overridePendingTransition(R.anim.fade_in, R.anim.scale_out); // } // // public void showMakeMarkerTop(){ // Intent intent = new Intent(this, ActivityMakeMarkerTop.class); // startActivity(intent); // } // // public void showAbout(){ // Intent intent = new Intent(this, ActivityAbout.class); // startActivity(intent); // } // } // Path: ARMusicKit/app/src/main/java/com/yurisuzuki/fragment/FragmentMenu.java import android.app.Fragment; import android.graphics.Typeface; import android.os.Bundle; import android.text.Spannable; import android.text.SpannableString; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.yurisuzuki.CustomTypefaceSpan; import com.yurisuzuki.MainActivity; import com.yurisuzuki.playsound.R; import java.util.ArrayList; } public void configureMenus(){ Typeface tfLight = Typeface.createFromAsset(getActivity().getAssets(), "fonts/HelveticaNeueLTStd-Lt.otf"); Typeface tfBold = Typeface.createFromAsset(getActivity().getAssets(), "fonts/HelveticaNeueLTStd-Bd.otf"); for(TextView textView : textViews){ final String text = (String)textView.getText(); String[] list = text.split(" "); String firstWord = list[0]; String secondWord = null; if(list.length > 1){ firstWord += " "; secondWord = list[1]; if(list.length == 3){ secondWord = secondWord + " " + list[2]; } }else{ secondWord = ""; } // Create a new spannable with the two strings Spannable spannable = new SpannableString(firstWord+secondWord); // Set the custom typeface to span over a section of the spannable object
spannable.setSpan( new CustomTypefaceSpan("sans-serif",tfLight), 0, firstWord.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
yurisuzukiltd/AR-Music-Kit
ARMusicKit/app/src/main/java/com/yurisuzuki/fragment/FragmentMenu.java
// Path: ARMusicKit/app/src/main/java/com/yurisuzuki/CustomTypefaceSpan.java // public class CustomTypefaceSpan extends TypefaceSpan { // private final Typeface newType; // // public CustomTypefaceSpan(String family, Typeface type) { // super(family); // newType = type; // } // // @Override // public void updateDrawState(TextPaint ds) { // applyCustomTypeFace(ds, newType); // } // // @Override // public void updateMeasureState(TextPaint paint) { // applyCustomTypeFace(paint, newType); // } // // private static void applyCustomTypeFace(Paint paint, Typeface tf) { // int oldStyle; // Typeface old = paint.getTypeface(); // if (old == null) { // oldStyle = 0; // } else { // oldStyle = old.getStyle(); // } // // int fake = oldStyle & ~tf.getStyle(); // if ((fake & Typeface.BOLD) != 0) { // paint.setFakeBoldText(true); // } // // if ((fake & Typeface.ITALIC) != 0) { // paint.setTextSkewX(-0.25f); // } // // paint.setTypeface(tf); // } // } // // Path: ARMusicKit/app/src/main/java/com/yurisuzuki/MainActivity.java // public class MainActivity extends Activity { // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_main); // // android.app.FragmentManager fm = getFragmentManager(); // FragmentMenu fragment = (FragmentMenu) fm.findFragmentByTag("FragmentMenu"); // if (fragment == null) { // fragment = FragmentMenu.newInstance(); // } // // if(fragment.isAdded() == false){ // fm.beginTransaction() // .add(R.id.main_container, fragment, "FragmentMenu") // .commit(); // } // // } // // public void jumpToCamera(){ // Intent intent = new Intent(this, CameraActivity.class); // startActivity(intent); // //finish(); // //overridePendingTransition(R.anim.fade_in, R.anim.scale_out); // } // // // public void showInstruction(String tag) { // Intent intent = new Intent(this, ActivityIntro.class); // intent.putExtra("type", tag); // startActivity(intent); // //finish(); // //overridePendingTransition(R.anim.fade_in, R.anim.scale_out); // } // // public void showMakeMarkerTop(){ // Intent intent = new Intent(this, ActivityMakeMarkerTop.class); // startActivity(intent); // } // // public void showAbout(){ // Intent intent = new Intent(this, ActivityAbout.class); // startActivity(intent); // } // }
import android.app.Fragment; import android.graphics.Typeface; import android.os.Bundle; import android.text.Spannable; import android.text.SpannableString; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.yurisuzuki.CustomTypefaceSpan; import com.yurisuzuki.MainActivity; import com.yurisuzuki.playsound.R; import java.util.ArrayList;
String[] list = text.split(" "); String firstWord = list[0]; String secondWord = null; if(list.length > 1){ firstWord += " "; secondWord = list[1]; if(list.length == 3){ secondWord = secondWord + " " + list[2]; } }else{ secondWord = ""; } // Create a new spannable with the two strings Spannable spannable = new SpannableString(firstWord+secondWord); // Set the custom typeface to span over a section of the spannable object spannable.setSpan( new CustomTypefaceSpan("sans-serif",tfLight), 0, firstWord.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); spannable.setSpan( new CustomTypefaceSpan("sans-serif",tfBold), firstWord.length(), firstWord.length() + secondWord.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); textView.setText(spannable); textView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //((MainActivity)getActivity()).openInstruction(); String tag = (String)v.getTag(); if(tag.equals("marker")){
// Path: ARMusicKit/app/src/main/java/com/yurisuzuki/CustomTypefaceSpan.java // public class CustomTypefaceSpan extends TypefaceSpan { // private final Typeface newType; // // public CustomTypefaceSpan(String family, Typeface type) { // super(family); // newType = type; // } // // @Override // public void updateDrawState(TextPaint ds) { // applyCustomTypeFace(ds, newType); // } // // @Override // public void updateMeasureState(TextPaint paint) { // applyCustomTypeFace(paint, newType); // } // // private static void applyCustomTypeFace(Paint paint, Typeface tf) { // int oldStyle; // Typeface old = paint.getTypeface(); // if (old == null) { // oldStyle = 0; // } else { // oldStyle = old.getStyle(); // } // // int fake = oldStyle & ~tf.getStyle(); // if ((fake & Typeface.BOLD) != 0) { // paint.setFakeBoldText(true); // } // // if ((fake & Typeface.ITALIC) != 0) { // paint.setTextSkewX(-0.25f); // } // // paint.setTypeface(tf); // } // } // // Path: ARMusicKit/app/src/main/java/com/yurisuzuki/MainActivity.java // public class MainActivity extends Activity { // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_main); // // android.app.FragmentManager fm = getFragmentManager(); // FragmentMenu fragment = (FragmentMenu) fm.findFragmentByTag("FragmentMenu"); // if (fragment == null) { // fragment = FragmentMenu.newInstance(); // } // // if(fragment.isAdded() == false){ // fm.beginTransaction() // .add(R.id.main_container, fragment, "FragmentMenu") // .commit(); // } // // } // // public void jumpToCamera(){ // Intent intent = new Intent(this, CameraActivity.class); // startActivity(intent); // //finish(); // //overridePendingTransition(R.anim.fade_in, R.anim.scale_out); // } // // // public void showInstruction(String tag) { // Intent intent = new Intent(this, ActivityIntro.class); // intent.putExtra("type", tag); // startActivity(intent); // //finish(); // //overridePendingTransition(R.anim.fade_in, R.anim.scale_out); // } // // public void showMakeMarkerTop(){ // Intent intent = new Intent(this, ActivityMakeMarkerTop.class); // startActivity(intent); // } // // public void showAbout(){ // Intent intent = new Intent(this, ActivityAbout.class); // startActivity(intent); // } // } // Path: ARMusicKit/app/src/main/java/com/yurisuzuki/fragment/FragmentMenu.java import android.app.Fragment; import android.graphics.Typeface; import android.os.Bundle; import android.text.Spannable; import android.text.SpannableString; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.yurisuzuki.CustomTypefaceSpan; import com.yurisuzuki.MainActivity; import com.yurisuzuki.playsound.R; import java.util.ArrayList; String[] list = text.split(" "); String firstWord = list[0]; String secondWord = null; if(list.length > 1){ firstWord += " "; secondWord = list[1]; if(list.length == 3){ secondWord = secondWord + " " + list[2]; } }else{ secondWord = ""; } // Create a new spannable with the two strings Spannable spannable = new SpannableString(firstWord+secondWord); // Set the custom typeface to span over a section of the spannable object spannable.setSpan( new CustomTypefaceSpan("sans-serif",tfLight), 0, firstWord.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); spannable.setSpan( new CustomTypefaceSpan("sans-serif",tfBold), firstWord.length(), firstWord.length() + secondWord.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); textView.setText(spannable); textView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //((MainActivity)getActivity()).openInstruction(); String tag = (String)v.getTag(); if(tag.equals("marker")){
((MainActivity)getActivity()).showMakeMarkerTop();
yurisuzukiltd/AR-Music-Kit
ARMusicKit/app/src/main/java/com/yurisuzuki/fragment/FragmentIntroBase.java
// Path: ARMusicKit/app/src/main/java/com/yurisuzuki/ActivityIntro.java // public class ActivityIntro extends Activity { // public static final String TAG = "ActivityIntro"; // private String type; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_intro); // // Bundle extras = getIntent().getExtras(); // if (extras != null) { // type = extras.getString("type"); // } // // showIntro(); // } // // private void showIntro(){ // //ActionBar actionBar = getActionBar(); // //actionBar.hide(); // // Fragment fragment = FragmentIntroBase.newInstance(type); // // getFragmentManager() // .beginTransaction() // .add(R.id.container, fragment, // "FragmentIntroBase").commit(); // } // // // public void jumpToCamera(){ // Intent intent = new Intent(this, CameraActivity.class); // intent.putExtra("type", type); // startActivity(intent); // //finish(); // //overridePendingTransition(R.anim.fade_in, R.anim.scale_out); // } // // // //@Override // /* // public boolean onCreateOptionsMenu(Menu menu) { // // Inflate the menu; this adds items to the action bar if it is present. // getMenuInflater().inflate(R.menu.menu_activity_intro, menu); // return true; // } // */ // // @Override // public boolean onOptionsItemSelected(MenuItem item) { // // Handle action bar item clicks here. The action bar will // // automatically handle clicks on the Home/Up button, so long // // as you specify a parent activity in AndroidManifest.xml. // // /* // int id = item.getItemId(); // // //noinspection SimplifiableIfStatement // if (id == R.id.action_settings) { // return true; // } // */ // // return super.onOptionsItemSelected(item); // } // }
import android.app.Activity; import android.app.Fragment; import android.os.Bundle; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import com.viewpagerindicator.CirclePageIndicator; import com.viewpagerindicator.PageIndicator; import com.yurisuzuki.ActivityIntro; import com.yurisuzuki.playsound.R;
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_intro_base, container, false); TextView titleView = (TextView)view.findViewById(R.id.inst_title); if(type != null){ int title; if(type.equals("guitar")){ title = R.string.inst_title_guitar; }else if(type.equals("piano")){ title = R.string.inst_title_piano; }else if(type.equals("musicbox")){ title = R.string.inst_title_mb; }else if(type.equals("trace")){ title = R.string.inst_title_trace; }else{ title = R.string.inst_title_trace; } titleView.setText(title); } Button startButton = (Button)view.findViewById(R.id.get_started_button); startButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { viewPager.setCurrentItem(0);
// Path: ARMusicKit/app/src/main/java/com/yurisuzuki/ActivityIntro.java // public class ActivityIntro extends Activity { // public static final String TAG = "ActivityIntro"; // private String type; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_intro); // // Bundle extras = getIntent().getExtras(); // if (extras != null) { // type = extras.getString("type"); // } // // showIntro(); // } // // private void showIntro(){ // //ActionBar actionBar = getActionBar(); // //actionBar.hide(); // // Fragment fragment = FragmentIntroBase.newInstance(type); // // getFragmentManager() // .beginTransaction() // .add(R.id.container, fragment, // "FragmentIntroBase").commit(); // } // // // public void jumpToCamera(){ // Intent intent = new Intent(this, CameraActivity.class); // intent.putExtra("type", type); // startActivity(intent); // //finish(); // //overridePendingTransition(R.anim.fade_in, R.anim.scale_out); // } // // // //@Override // /* // public boolean onCreateOptionsMenu(Menu menu) { // // Inflate the menu; this adds items to the action bar if it is present. // getMenuInflater().inflate(R.menu.menu_activity_intro, menu); // return true; // } // */ // // @Override // public boolean onOptionsItemSelected(MenuItem item) { // // Handle action bar item clicks here. The action bar will // // automatically handle clicks on the Home/Up button, so long // // as you specify a parent activity in AndroidManifest.xml. // // /* // int id = item.getItemId(); // // //noinspection SimplifiableIfStatement // if (id == R.id.action_settings) { // return true; // } // */ // // return super.onOptionsItemSelected(item); // } // } // Path: ARMusicKit/app/src/main/java/com/yurisuzuki/fragment/FragmentIntroBase.java import android.app.Activity; import android.app.Fragment; import android.os.Bundle; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import com.viewpagerindicator.CirclePageIndicator; import com.viewpagerindicator.PageIndicator; import com.yurisuzuki.ActivityIntro; import com.yurisuzuki.playsound.R; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_intro_base, container, false); TextView titleView = (TextView)view.findViewById(R.id.inst_title); if(type != null){ int title; if(type.equals("guitar")){ title = R.string.inst_title_guitar; }else if(type.equals("piano")){ title = R.string.inst_title_piano; }else if(type.equals("musicbox")){ title = R.string.inst_title_mb; }else if(type.equals("trace")){ title = R.string.inst_title_trace; }else{ title = R.string.inst_title_trace; } titleView.setText(title); } Button startButton = (Button)view.findViewById(R.id.get_started_button); startButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { viewPager.setCurrentItem(0);
((ActivityIntro)FragmentIntroBase.this.getActivity()).jumpToCamera();
yurisuzukiltd/AR-Music-Kit
ARMusicKit/app/src/main/java/com/yurisuzuki/ar/Marker.java
// Path: ARMusicKit/base/src/main/java/org/artoolkit/ar/base/camera/CameraRotationInfo.java // public class CameraRotationInfo { // // 基準からの回転角度 // public int rotation; // // // 左右反転必要かどうか // public boolean mirror; // // /** // * @param rotation setCameraDisplayOrientation()のboilarplateで、最後に算出されたresult角度. // * @param front フロントカメラかどうか // */ // public CameraRotationInfo(int rotation, boolean front) { // if( front ) { // // フロントカメラは180度がベース // this.rotation = (rotation + 180) % 360; // // 鏡面反転する // this.mirror = true; // } else { // // リアカメラは0度がベース // this.rotation = rotation; // // 鏡面反転しない // this.mirror = false; // } // } // }
import javax.microedition.khronos.opengles.GL10; import android.content.Context; import org.artoolkit.ar.base.ARToolKit; import org.artoolkit.ar.base.camera.CameraRotationInfo;
} /** * マーカー認識時に表示するテクスチャ(ストライプ画像)をロード * (MusicBoxの場合は呼ばれない) */ boolean loadMarkerTexture(GL10 gl, Context context, String textureAssetPath) { return markerPlane.loadGLTexture(gl, context, textureAssetPath); } /** * 発音時に表示するテクスチャ(パッ画像)をロード */ boolean loadActionTexture(GL10 gl, Context context, String textureAssetPath) { return actionPlane.loadGLTexture(gl, context, textureAssetPath); } protected boolean isTracked() { ARToolKit ar = ARToolKit.getInstance(); return ar.queryMarkerVisible(markerId); } protected void cacheMarkerMatrix(float markerMatrix[]) { if (cachedMarkerMatrix == null || cachedMarkerMatrix.length != markerMatrix.length) { cachedMarkerMatrix = new float[markerMatrix.length]; } System.arraycopy(markerMatrix, 0, cachedMarkerMatrix, 0, markerMatrix.length); markerMatrixCached = true; }
// Path: ARMusicKit/base/src/main/java/org/artoolkit/ar/base/camera/CameraRotationInfo.java // public class CameraRotationInfo { // // 基準からの回転角度 // public int rotation; // // // 左右反転必要かどうか // public boolean mirror; // // /** // * @param rotation setCameraDisplayOrientation()のboilarplateで、最後に算出されたresult角度. // * @param front フロントカメラかどうか // */ // public CameraRotationInfo(int rotation, boolean front) { // if( front ) { // // フロントカメラは180度がベース // this.rotation = (rotation + 180) % 360; // // 鏡面反転する // this.mirror = true; // } else { // // リアカメラは0度がベース // this.rotation = rotation; // // 鏡面反転しない // this.mirror = false; // } // } // } // Path: ARMusicKit/app/src/main/java/com/yurisuzuki/ar/Marker.java import javax.microedition.khronos.opengles.GL10; import android.content.Context; import org.artoolkit.ar.base.ARToolKit; import org.artoolkit.ar.base.camera.CameraRotationInfo; } /** * マーカー認識時に表示するテクスチャ(ストライプ画像)をロード * (MusicBoxの場合は呼ばれない) */ boolean loadMarkerTexture(GL10 gl, Context context, String textureAssetPath) { return markerPlane.loadGLTexture(gl, context, textureAssetPath); } /** * 発音時に表示するテクスチャ(パッ画像)をロード */ boolean loadActionTexture(GL10 gl, Context context, String textureAssetPath) { return actionPlane.loadGLTexture(gl, context, textureAssetPath); } protected boolean isTracked() { ARToolKit ar = ARToolKit.getInstance(); return ar.queryMarkerVisible(markerId); } protected void cacheMarkerMatrix(float markerMatrix[]) { if (cachedMarkerMatrix == null || cachedMarkerMatrix.length != markerMatrix.length) { cachedMarkerMatrix = new float[markerMatrix.length]; } System.arraycopy(markerMatrix, 0, cachedMarkerMatrix, 0, markerMatrix.length); markerMatrixCached = true; }
protected void adjustMarkerMatrix(float[] matrix, float[] targetMatrix, CameraRotationInfo cameraRotationInfo) {
liuyes/ssopay-qywx
ssopay-qywx-common/src/main/java/com/ssopay/qywx/util/Digests.java
// Path: ssopay-qywx-common/src/main/java/com/ssopay/qywx/base/Exceptions.java // public class Exceptions extends RuntimeException { // private static final long serialVersionUID = -6695188947450520803L; // private String key; // // private Object[] values; // // public Exceptions() { // super(); // } // // public Exceptions(String message, Throwable throwable) { // super(message, throwable); // } // // public Exceptions(String message) { // super(message); // } // // public Exceptions(Throwable throwable) { // super(throwable); // } // // public Exceptions(String message,String key){ // super(message); // this.key = key; // } // // public Exceptions(String message,String key,Object value){ // super(message); // this.key = key; // this.values = new Object[]{value}; // } // // public Exceptions(String message,String key,Object[] values){ // super(message); // this.key = key; // this.values = values; // } // // public String getKey() { // return key; // } // // public Object[] getValues() { // return values; // } // // }
import java.io.IOException; import java.io.InputStream; import java.security.GeneralSecurityException; import java.security.MessageDigest; import java.security.SecureRandom; import org.apache.commons.lang3.Validate; import com.ssopay.qywx.base.Exceptions;
/** * Copyright (c) 2005-2012 springside.org.cn * * Licensed under the Apache License, Version 2.0 (the "License"); */ package com.ssopay.qywx.util; /** * 支持SHA-1/MD5消息摘要的工具类. * * 返回ByteSource,可进一步被编码为Hex, Base64或UrlSafeBase64 * * @author calvin */ public class Digests { private static final String SHA1 = "SHA-1"; private static final String MD5 = "MD5"; private static SecureRandom random = new SecureRandom(); /** * 对输入字符串进行sha1散列. */ public static byte[] sha1(byte[] input) { return digest(input, SHA1, null, 1); } public static byte[] sha1(byte[] input, byte[] salt) { return digest(input, SHA1, salt, 1); } public static byte[] sha1(byte[] input, byte[] salt, int iterations) { return digest(input, SHA1, salt, iterations); } /** * 对字符串进行散列, 支持md5与sha1算法. */ private static byte[] digest(byte[] input, String algorithm, byte[] salt, int iterations) { try { MessageDigest digest = MessageDigest.getInstance(algorithm); if (salt != null) { digest.update(salt); } byte[] result = digest.digest(input); for (int i = 1; i < iterations; i++) { digest.reset(); result = digest.digest(result); } return result; } catch (GeneralSecurityException e) {
// Path: ssopay-qywx-common/src/main/java/com/ssopay/qywx/base/Exceptions.java // public class Exceptions extends RuntimeException { // private static final long serialVersionUID = -6695188947450520803L; // private String key; // // private Object[] values; // // public Exceptions() { // super(); // } // // public Exceptions(String message, Throwable throwable) { // super(message, throwable); // } // // public Exceptions(String message) { // super(message); // } // // public Exceptions(Throwable throwable) { // super(throwable); // } // // public Exceptions(String message,String key){ // super(message); // this.key = key; // } // // public Exceptions(String message,String key,Object value){ // super(message); // this.key = key; // this.values = new Object[]{value}; // } // // public Exceptions(String message,String key,Object[] values){ // super(message); // this.key = key; // this.values = values; // } // // public String getKey() { // return key; // } // // public Object[] getValues() { // return values; // } // // } // Path: ssopay-qywx-common/src/main/java/com/ssopay/qywx/util/Digests.java import java.io.IOException; import java.io.InputStream; import java.security.GeneralSecurityException; import java.security.MessageDigest; import java.security.SecureRandom; import org.apache.commons.lang3.Validate; import com.ssopay.qywx.base.Exceptions; /** * Copyright (c) 2005-2012 springside.org.cn * * Licensed under the Apache License, Version 2.0 (the "License"); */ package com.ssopay.qywx.util; /** * 支持SHA-1/MD5消息摘要的工具类. * * 返回ByteSource,可进一步被编码为Hex, Base64或UrlSafeBase64 * * @author calvin */ public class Digests { private static final String SHA1 = "SHA-1"; private static final String MD5 = "MD5"; private static SecureRandom random = new SecureRandom(); /** * 对输入字符串进行sha1散列. */ public static byte[] sha1(byte[] input) { return digest(input, SHA1, null, 1); } public static byte[] sha1(byte[] input, byte[] salt) { return digest(input, SHA1, salt, 1); } public static byte[] sha1(byte[] input, byte[] salt, int iterations) { return digest(input, SHA1, salt, iterations); } /** * 对字符串进行散列, 支持md5与sha1算法. */ private static byte[] digest(byte[] input, String algorithm, byte[] salt, int iterations) { try { MessageDigest digest = MessageDigest.getInstance(algorithm); if (salt != null) { digest.update(salt); } byte[] result = digest.digest(input); for (int i = 1; i < iterations; i++) { digest.reset(); result = digest.digest(result); } return result; } catch (GeneralSecurityException e) {
throw new Exceptions("未经检查的异常。");
liuyes/ssopay-qywx
ssopay-qywx-admin/src/main/java/com/ssopay/qywx/login/web/LoginController.java
// Path: ssopay-qywx-bean/src/main/java/com/ssopay/qywx/base/Result.java // public class Result implements Serializable { // private static final long serialVersionUID = 1L; // // private Integer code = -1; // private String msg; // private String url; // private Long time = new Date().getTime(); // private List<ResultMap> data; // public Integer getCode() { // return code; // } // public void setCode(Integer code) { // this.code = code; // } // public String getMsg() { // return msg; // } // public void setMsg(String msg) { // this.msg = msg; // } // public String getUrl() { // return url; // } // public void setUrl(String url) { // this.url = url; // } // public Long getTime() { // return time; // } // public void setTime(Long time) { // this.time = time; // } // public List<ResultMap> getData() { // return data; // } // public void setData(List<ResultMap> data) { // this.data = data; // } // // } // // Path: ssopay-qywx-admin/src/main/java/com/ssopay/qywx/jcaptcha/JCaptchaServiceSingleton.java // public class JCaptchaServiceSingleton { // // private static ImageCaptchaService instance = null; // // private JCaptchaServiceSingleton() { // } // // // 使用synchronized关键字解决线程不安全 // public synchronized static ImageCaptchaService getInstance() { // if (instance == null) { // instance = new DefaultManageableImageCaptchaService( // new FastHashMapCaptchaStore(), new GMailEngine(), 180, // 100000, 75000); // } // return instance; // } // // }
import java.awt.image.BufferedImage; import java.io.IOException; import java.util.Random; import javax.imageio.ImageIO; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.shiro.web.filter.authc.FormAuthenticationFilter; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.ssopay.qywx.base.Result; import com.ssopay.qywx.jcaptcha.JCaptchaServiceSingleton;
package com.ssopay.qywx.login.web; /** * * @ClassName: LoginController * @Description: TODO(负责打开登录页面(GET请求)和登录出错页面(POST请求),真正登录的POST请求由Filter完成) * @author ssopay * @date 2017年7月6日 下午3:55:28 * */ @Controller public class LoginController { @RequestMapping(value = "login", method = RequestMethod.GET) public String login(Model model) { //生成一个四位随机数给登录面使用,每次背景不同 1000-3999之间 Random random = new Random(); int x = random.nextInt(3999 - 1000 + 1) + 1000; model.addAttribute("random", x); return "login"; } @RequestMapping(value = "login", method = RequestMethod.POST) @ResponseBody
// Path: ssopay-qywx-bean/src/main/java/com/ssopay/qywx/base/Result.java // public class Result implements Serializable { // private static final long serialVersionUID = 1L; // // private Integer code = -1; // private String msg; // private String url; // private Long time = new Date().getTime(); // private List<ResultMap> data; // public Integer getCode() { // return code; // } // public void setCode(Integer code) { // this.code = code; // } // public String getMsg() { // return msg; // } // public void setMsg(String msg) { // this.msg = msg; // } // public String getUrl() { // return url; // } // public void setUrl(String url) { // this.url = url; // } // public Long getTime() { // return time; // } // public void setTime(Long time) { // this.time = time; // } // public List<ResultMap> getData() { // return data; // } // public void setData(List<ResultMap> data) { // this.data = data; // } // // } // // Path: ssopay-qywx-admin/src/main/java/com/ssopay/qywx/jcaptcha/JCaptchaServiceSingleton.java // public class JCaptchaServiceSingleton { // // private static ImageCaptchaService instance = null; // // private JCaptchaServiceSingleton() { // } // // // 使用synchronized关键字解决线程不安全 // public synchronized static ImageCaptchaService getInstance() { // if (instance == null) { // instance = new DefaultManageableImageCaptchaService( // new FastHashMapCaptchaStore(), new GMailEngine(), 180, // 100000, 75000); // } // return instance; // } // // } // Path: ssopay-qywx-admin/src/main/java/com/ssopay/qywx/login/web/LoginController.java import java.awt.image.BufferedImage; import java.io.IOException; import java.util.Random; import javax.imageio.ImageIO; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.shiro.web.filter.authc.FormAuthenticationFilter; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.ssopay.qywx.base.Result; import com.ssopay.qywx.jcaptcha.JCaptchaServiceSingleton; package com.ssopay.qywx.login.web; /** * * @ClassName: LoginController * @Description: TODO(负责打开登录页面(GET请求)和登录出错页面(POST请求),真正登录的POST请求由Filter完成) * @author ssopay * @date 2017年7月6日 下午3:55:28 * */ @Controller public class LoginController { @RequestMapping(value = "login", method = RequestMethod.GET) public String login(Model model) { //生成一个四位随机数给登录面使用,每次背景不同 1000-3999之间 Random random = new Random(); int x = random.nextInt(3999 - 1000 + 1) + 1000; model.addAttribute("random", x); return "login"; } @RequestMapping(value = "login", method = RequestMethod.POST) @ResponseBody
public Result fail(String username, HttpServletRequest request) {
liuyes/ssopay-qywx
ssopay-qywx-admin/src/main/java/com/ssopay/qywx/login/web/LoginController.java
// Path: ssopay-qywx-bean/src/main/java/com/ssopay/qywx/base/Result.java // public class Result implements Serializable { // private static final long serialVersionUID = 1L; // // private Integer code = -1; // private String msg; // private String url; // private Long time = new Date().getTime(); // private List<ResultMap> data; // public Integer getCode() { // return code; // } // public void setCode(Integer code) { // this.code = code; // } // public String getMsg() { // return msg; // } // public void setMsg(String msg) { // this.msg = msg; // } // public String getUrl() { // return url; // } // public void setUrl(String url) { // this.url = url; // } // public Long getTime() { // return time; // } // public void setTime(Long time) { // this.time = time; // } // public List<ResultMap> getData() { // return data; // } // public void setData(List<ResultMap> data) { // this.data = data; // } // // } // // Path: ssopay-qywx-admin/src/main/java/com/ssopay/qywx/jcaptcha/JCaptchaServiceSingleton.java // public class JCaptchaServiceSingleton { // // private static ImageCaptchaService instance = null; // // private JCaptchaServiceSingleton() { // } // // // 使用synchronized关键字解决线程不安全 // public synchronized static ImageCaptchaService getInstance() { // if (instance == null) { // instance = new DefaultManageableImageCaptchaService( // new FastHashMapCaptchaStore(), new GMailEngine(), 180, // 100000, 75000); // } // return instance; // } // // }
import java.awt.image.BufferedImage; import java.io.IOException; import java.util.Random; import javax.imageio.ImageIO; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.shiro.web.filter.authc.FormAuthenticationFilter; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.ssopay.qywx.base.Result; import com.ssopay.qywx.jcaptcha.JCaptchaServiceSingleton;
@ResponseBody public Result fail(String username, HttpServletRequest request) { Result result = new Result(); Object obj = request.getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME); String msg = ""; if(obj != null){ if("captcha.error".equals(obj)) msg = ",验证码错误"; else if("org.apache.shiro.authc.UnknownAccountException".equals(obj)) msg = ",帐号或密码错误"; else if("org.apache.shiro.authc.IncorrectCredentialsException".equals(obj)) msg = ",帐号或密码错误"; else if("org.apache.shiro.authc.AuthenticationException".equals(obj)) msg = ",认证失败,请重试"; } result.setMsg(username + "登录失败" + msg); return result; } @RequestMapping("code") public void code(HttpServletResponse response, HttpServletRequest request) throws Exception{ response.setHeader("Cache-Control", "no-store"); response.setHeader("Pragma", "no-cache"); response.setDateHeader("Expires", 0); response.setContentType("image/jpeg"); ServletOutputStream sos = null; try { sos = response.getOutputStream(); String sid = request.getRequestedSessionId();
// Path: ssopay-qywx-bean/src/main/java/com/ssopay/qywx/base/Result.java // public class Result implements Serializable { // private static final long serialVersionUID = 1L; // // private Integer code = -1; // private String msg; // private String url; // private Long time = new Date().getTime(); // private List<ResultMap> data; // public Integer getCode() { // return code; // } // public void setCode(Integer code) { // this.code = code; // } // public String getMsg() { // return msg; // } // public void setMsg(String msg) { // this.msg = msg; // } // public String getUrl() { // return url; // } // public void setUrl(String url) { // this.url = url; // } // public Long getTime() { // return time; // } // public void setTime(Long time) { // this.time = time; // } // public List<ResultMap> getData() { // return data; // } // public void setData(List<ResultMap> data) { // this.data = data; // } // // } // // Path: ssopay-qywx-admin/src/main/java/com/ssopay/qywx/jcaptcha/JCaptchaServiceSingleton.java // public class JCaptchaServiceSingleton { // // private static ImageCaptchaService instance = null; // // private JCaptchaServiceSingleton() { // } // // // 使用synchronized关键字解决线程不安全 // public synchronized static ImageCaptchaService getInstance() { // if (instance == null) { // instance = new DefaultManageableImageCaptchaService( // new FastHashMapCaptchaStore(), new GMailEngine(), 180, // 100000, 75000); // } // return instance; // } // // } // Path: ssopay-qywx-admin/src/main/java/com/ssopay/qywx/login/web/LoginController.java import java.awt.image.BufferedImage; import java.io.IOException; import java.util.Random; import javax.imageio.ImageIO; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.shiro.web.filter.authc.FormAuthenticationFilter; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.ssopay.qywx.base.Result; import com.ssopay.qywx.jcaptcha.JCaptchaServiceSingleton; @ResponseBody public Result fail(String username, HttpServletRequest request) { Result result = new Result(); Object obj = request.getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME); String msg = ""; if(obj != null){ if("captcha.error".equals(obj)) msg = ",验证码错误"; else if("org.apache.shiro.authc.UnknownAccountException".equals(obj)) msg = ",帐号或密码错误"; else if("org.apache.shiro.authc.IncorrectCredentialsException".equals(obj)) msg = ",帐号或密码错误"; else if("org.apache.shiro.authc.AuthenticationException".equals(obj)) msg = ",认证失败,请重试"; } result.setMsg(username + "登录失败" + msg); return result; } @RequestMapping("code") public void code(HttpServletResponse response, HttpServletRequest request) throws Exception{ response.setHeader("Cache-Control", "no-store"); response.setHeader("Pragma", "no-cache"); response.setDateHeader("Expires", 0); response.setContentType("image/jpeg"); ServletOutputStream sos = null; try { sos = response.getOutputStream(); String sid = request.getRequestedSessionId();
BufferedImage challenge = JCaptchaServiceSingleton.getInstance().getImageChallengeForID(sid);
liuyes/ssopay-qywx
ssopay-qywx-common/src/main/java/com/ssopay/qywx/util/Encodes.java
// Path: ssopay-qywx-common/src/main/java/com/ssopay/qywx/base/Exceptions.java // public class Exceptions extends RuntimeException { // private static final long serialVersionUID = -6695188947450520803L; // private String key; // // private Object[] values; // // public Exceptions() { // super(); // } // // public Exceptions(String message, Throwable throwable) { // super(message, throwable); // } // // public Exceptions(String message) { // super(message); // } // // public Exceptions(Throwable throwable) { // super(throwable); // } // // public Exceptions(String message,String key){ // super(message); // this.key = key; // } // // public Exceptions(String message,String key,Object value){ // super(message); // this.key = key; // this.values = new Object[]{value}; // } // // public Exceptions(String message,String key,Object[] values){ // super(message); // this.key = key; // this.values = values; // } // // public String getKey() { // return key; // } // // public Object[] getValues() { // return values; // } // // }
import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; import org.apache.commons.codec.DecoderException; import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Hex; import org.apache.commons.lang3.StringEscapeUtils; import com.ssopay.qywx.base.Exceptions;
/** * Copyright (c) 2005-2012 springside.org.cn * * Licensed under the Apache License, Version 2.0 (the "License"); */ package com.ssopay.qywx.util; /** * 封装各种格式的编码解码工具类. * * 1.Commons-Codec的 hex/base64 编码 * 2.自制的base62 编码 * 3.Commons-Lang的xml/html escape * 4.JDK提供的URLEncoder * * @author calvin */ public class Encodes { private static final String DEFAULT_URL_ENCODING = "UTF-8"; private static final char[] BASE62 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".toCharArray(); /** * Hex编码. */ public static String encodeHex(byte[] input) { return Hex.encodeHexString(input); } /** * Hex解码. */ public static byte[] decodeHex(String input) { try { return Hex.decodeHex(input.toCharArray()); } catch (DecoderException e) {
// Path: ssopay-qywx-common/src/main/java/com/ssopay/qywx/base/Exceptions.java // public class Exceptions extends RuntimeException { // private static final long serialVersionUID = -6695188947450520803L; // private String key; // // private Object[] values; // // public Exceptions() { // super(); // } // // public Exceptions(String message, Throwable throwable) { // super(message, throwable); // } // // public Exceptions(String message) { // super(message); // } // // public Exceptions(Throwable throwable) { // super(throwable); // } // // public Exceptions(String message,String key){ // super(message); // this.key = key; // } // // public Exceptions(String message,String key,Object value){ // super(message); // this.key = key; // this.values = new Object[]{value}; // } // // public Exceptions(String message,String key,Object[] values){ // super(message); // this.key = key; // this.values = values; // } // // public String getKey() { // return key; // } // // public Object[] getValues() { // return values; // } // // } // Path: ssopay-qywx-common/src/main/java/com/ssopay/qywx/util/Encodes.java import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; import org.apache.commons.codec.DecoderException; import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Hex; import org.apache.commons.lang3.StringEscapeUtils; import com.ssopay.qywx.base.Exceptions; /** * Copyright (c) 2005-2012 springside.org.cn * * Licensed under the Apache License, Version 2.0 (the "License"); */ package com.ssopay.qywx.util; /** * 封装各种格式的编码解码工具类. * * 1.Commons-Codec的 hex/base64 编码 * 2.自制的base62 编码 * 3.Commons-Lang的xml/html escape * 4.JDK提供的URLEncoder * * @author calvin */ public class Encodes { private static final String DEFAULT_URL_ENCODING = "UTF-8"; private static final char[] BASE62 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".toCharArray(); /** * Hex编码. */ public static String encodeHex(byte[] input) { return Hex.encodeHexString(input); } /** * Hex解码. */ public static byte[] decodeHex(String input) { try { return Hex.decodeHex(input.toCharArray()); } catch (DecoderException e) {
throw new Exceptions("未经检查的异常。");
liuyes/ssopay-qywx
ssopay-qywx-admin/src/main/java/com/ssopay/qywx/upload/web/UploadController.java
// Path: ssopay-qywx-bean/src/main/java/com/ssopay/qywx/base/Result.java // public class Result implements Serializable { // private static final long serialVersionUID = 1L; // // private Integer code = -1; // private String msg; // private String url; // private Long time = new Date().getTime(); // private List<ResultMap> data; // public Integer getCode() { // return code; // } // public void setCode(Integer code) { // this.code = code; // } // public String getMsg() { // return msg; // } // public void setMsg(String msg) { // this.msg = msg; // } // public String getUrl() { // return url; // } // public void setUrl(String url) { // this.url = url; // } // public Long getTime() { // return time; // } // public void setTime(Long time) { // this.time = time; // } // public List<ResultMap> getData() { // return data; // } // public void setData(List<ResultMap> data) { // this.data = data; // } // // }
import org.apache.shiro.authz.annotation.RequiresUser; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.ssopay.qywx.base.Result;
package com.ssopay.qywx.upload.web; /** * * @ClassName: UploadController * @Description: TODO(文件上传类) * @author ssopay * @date 2017年8月7日 下午3:08:54 * */ @Controller @RequestMapping("/upload") public class UploadController { @RequiresUser @RequestMapping("") @ResponseBody
// Path: ssopay-qywx-bean/src/main/java/com/ssopay/qywx/base/Result.java // public class Result implements Serializable { // private static final long serialVersionUID = 1L; // // private Integer code = -1; // private String msg; // private String url; // private Long time = new Date().getTime(); // private List<ResultMap> data; // public Integer getCode() { // return code; // } // public void setCode(Integer code) { // this.code = code; // } // public String getMsg() { // return msg; // } // public void setMsg(String msg) { // this.msg = msg; // } // public String getUrl() { // return url; // } // public void setUrl(String url) { // this.url = url; // } // public Long getTime() { // return time; // } // public void setTime(Long time) { // this.time = time; // } // public List<ResultMap> getData() { // return data; // } // public void setData(List<ResultMap> data) { // this.data = data; // } // // } // Path: ssopay-qywx-admin/src/main/java/com/ssopay/qywx/upload/web/UploadController.java import org.apache.shiro.authz.annotation.RequiresUser; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.ssopay.qywx.base.Result; package com.ssopay.qywx.upload.web; /** * * @ClassName: UploadController * @Description: TODO(文件上传类) * @author ssopay * @date 2017年8月7日 下午3:08:54 * */ @Controller @RequestMapping("/upload") public class UploadController { @RequiresUser @RequestMapping("") @ResponseBody
public Result upload() {
cbartosiak/bson-codecs-jsr310
src/main/java/io/github/cbartosiak/bson/codecs/jsr310/localtime/LocalTimeAsDocumentCodec.java
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value> Value getFieldValue( // Document document, // Object key, // Class<Value> clazz) { // // try { // Value value = document.get(key, clazz); // if (value == null) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is null", key // )); // } // return value; // } // catch (ClassCastException ex) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is not of the type %s", // key, clazz.getName() // ), ex); // } // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static Document readDocument( // BsonReader reader, // DecoderContext decoderContext, // Map<String, Decoder<?>> fieldDecoders) { // // Document document = new Document(); // reader.readStartDocument(); // while (reader.readBsonType() != END_OF_DOCUMENT) { // String fieldName = reader.readName(); // if (fieldDecoders.containsKey(fieldName)) { // document.put( // fieldName, // fieldDecoders // .get(fieldName) // .decode(reader, decoderContext) // ); // } // else { // throw new BsonInvalidOperationException(format( // "The field %s is not expected here", fieldName // )); // } // } // reader.readEndDocument(); // return document; // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // }
import org.bson.codecs.Decoder; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.getFieldValue; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.readDocument; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static java.time.LocalTime.of; import static java.util.Collections.unmodifiableMap; import static java.util.Objects.requireNonNull; import java.time.LocalTime; import java.util.HashMap; import java.util.Map; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec;
/* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.localtime; /** * <p> * Encodes and decodes {@code LocalTime} values to and from * {@code BSON Document}, such as * {@code { hour: 10, minute: 15, second: 30, nano: 0 }}. * <p> * The values are stored using the following structure: * <ul> * <li>{@code hour} (a non-null {@code Int32}); * <li>{@code minute} (a non-null {@code Int32}); * <li>{@code second} (a non-null {@code Int32}); * <li>{@code nano} (a non-null {@code Int32}). * </ul> * <p> * This type is <b>immutable</b>. */ public final class LocalTimeAsDocumentCodec implements Codec<LocalTime> { private static final Map<String, Decoder<?>> FIELD_DECODERS; static { Map<String, Decoder<?>> fd = new HashMap<>(); fd.put("hour", (r, dc) -> r.readInt32()); fd.put("minute", (r, dc) -> r.readInt32()); fd.put("second", (r, dc) -> r.readInt32()); fd.put("nano", (r, dc) -> r.readInt32()); FIELD_DECODERS = unmodifiableMap(fd); } @Override public void encode( BsonWriter writer, LocalTime value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); writer.writeStartDocument(); writer.writeInt32("hour", value.getHour()); writer.writeInt32("minute", value.getMinute()); writer.writeInt32("second", value.getSecond()); writer.writeInt32("nano", value.getNano()); writer.writeEndDocument(); } @Override public LocalTime decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null");
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value> Value getFieldValue( // Document document, // Object key, // Class<Value> clazz) { // // try { // Value value = document.get(key, clazz); // if (value == null) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is null", key // )); // } // return value; // } // catch (ClassCastException ex) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is not of the type %s", // key, clazz.getName() // ), ex); // } // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static Document readDocument( // BsonReader reader, // DecoderContext decoderContext, // Map<String, Decoder<?>> fieldDecoders) { // // Document document = new Document(); // reader.readStartDocument(); // while (reader.readBsonType() != END_OF_DOCUMENT) { // String fieldName = reader.readName(); // if (fieldDecoders.containsKey(fieldName)) { // document.put( // fieldName, // fieldDecoders // .get(fieldName) // .decode(reader, decoderContext) // ); // } // else { // throw new BsonInvalidOperationException(format( // "The field %s is not expected here", fieldName // )); // } // } // reader.readEndDocument(); // return document; // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/localtime/LocalTimeAsDocumentCodec.java import org.bson.codecs.Decoder; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.getFieldValue; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.readDocument; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static java.time.LocalTime.of; import static java.util.Collections.unmodifiableMap; import static java.util.Objects.requireNonNull; import java.time.LocalTime; import java.util.HashMap; import java.util.Map; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; /* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.localtime; /** * <p> * Encodes and decodes {@code LocalTime} values to and from * {@code BSON Document}, such as * {@code { hour: 10, minute: 15, second: 30, nano: 0 }}. * <p> * The values are stored using the following structure: * <ul> * <li>{@code hour} (a non-null {@code Int32}); * <li>{@code minute} (a non-null {@code Int32}); * <li>{@code second} (a non-null {@code Int32}); * <li>{@code nano} (a non-null {@code Int32}). * </ul> * <p> * This type is <b>immutable</b>. */ public final class LocalTimeAsDocumentCodec implements Codec<LocalTime> { private static final Map<String, Decoder<?>> FIELD_DECODERS; static { Map<String, Decoder<?>> fd = new HashMap<>(); fd.put("hour", (r, dc) -> r.readInt32()); fd.put("minute", (r, dc) -> r.readInt32()); fd.put("second", (r, dc) -> r.readInt32()); fd.put("nano", (r, dc) -> r.readInt32()); FIELD_DECODERS = unmodifiableMap(fd); } @Override public void encode( BsonWriter writer, LocalTime value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); writer.writeStartDocument(); writer.writeInt32("hour", value.getHour()); writer.writeInt32("minute", value.getMinute()); writer.writeInt32("second", value.getSecond()); writer.writeInt32("nano", value.getNano()); writer.writeEndDocument(); } @Override public LocalTime decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null");
return translateDecodeExceptions(
cbartosiak/bson-codecs-jsr310
src/main/java/io/github/cbartosiak/bson/codecs/jsr310/localtime/LocalTimeAsDocumentCodec.java
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value> Value getFieldValue( // Document document, // Object key, // Class<Value> clazz) { // // try { // Value value = document.get(key, clazz); // if (value == null) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is null", key // )); // } // return value; // } // catch (ClassCastException ex) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is not of the type %s", // key, clazz.getName() // ), ex); // } // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static Document readDocument( // BsonReader reader, // DecoderContext decoderContext, // Map<String, Decoder<?>> fieldDecoders) { // // Document document = new Document(); // reader.readStartDocument(); // while (reader.readBsonType() != END_OF_DOCUMENT) { // String fieldName = reader.readName(); // if (fieldDecoders.containsKey(fieldName)) { // document.put( // fieldName, // fieldDecoders // .get(fieldName) // .decode(reader, decoderContext) // ); // } // else { // throw new BsonInvalidOperationException(format( // "The field %s is not expected here", fieldName // )); // } // } // reader.readEndDocument(); // return document; // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // }
import org.bson.codecs.Decoder; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.getFieldValue; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.readDocument; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static java.time.LocalTime.of; import static java.util.Collections.unmodifiableMap; import static java.util.Objects.requireNonNull; import java.time.LocalTime; import java.util.HashMap; import java.util.Map; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec;
fd.put("hour", (r, dc) -> r.readInt32()); fd.put("minute", (r, dc) -> r.readInt32()); fd.put("second", (r, dc) -> r.readInt32()); fd.put("nano", (r, dc) -> r.readInt32()); FIELD_DECODERS = unmodifiableMap(fd); } @Override public void encode( BsonWriter writer, LocalTime value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); writer.writeStartDocument(); writer.writeInt32("hour", value.getHour()); writer.writeInt32("minute", value.getMinute()); writer.writeInt32("second", value.getSecond()); writer.writeInt32("nano", value.getNano()); writer.writeEndDocument(); } @Override public LocalTime decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null"); return translateDecodeExceptions(
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value> Value getFieldValue( // Document document, // Object key, // Class<Value> clazz) { // // try { // Value value = document.get(key, clazz); // if (value == null) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is null", key // )); // } // return value; // } // catch (ClassCastException ex) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is not of the type %s", // key, clazz.getName() // ), ex); // } // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static Document readDocument( // BsonReader reader, // DecoderContext decoderContext, // Map<String, Decoder<?>> fieldDecoders) { // // Document document = new Document(); // reader.readStartDocument(); // while (reader.readBsonType() != END_OF_DOCUMENT) { // String fieldName = reader.readName(); // if (fieldDecoders.containsKey(fieldName)) { // document.put( // fieldName, // fieldDecoders // .get(fieldName) // .decode(reader, decoderContext) // ); // } // else { // throw new BsonInvalidOperationException(format( // "The field %s is not expected here", fieldName // )); // } // } // reader.readEndDocument(); // return document; // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/localtime/LocalTimeAsDocumentCodec.java import org.bson.codecs.Decoder; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.getFieldValue; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.readDocument; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static java.time.LocalTime.of; import static java.util.Collections.unmodifiableMap; import static java.util.Objects.requireNonNull; import java.time.LocalTime; import java.util.HashMap; import java.util.Map; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; fd.put("hour", (r, dc) -> r.readInt32()); fd.put("minute", (r, dc) -> r.readInt32()); fd.put("second", (r, dc) -> r.readInt32()); fd.put("nano", (r, dc) -> r.readInt32()); FIELD_DECODERS = unmodifiableMap(fd); } @Override public void encode( BsonWriter writer, LocalTime value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); writer.writeStartDocument(); writer.writeInt32("hour", value.getHour()); writer.writeInt32("minute", value.getMinute()); writer.writeInt32("second", value.getSecond()); writer.writeInt32("nano", value.getNano()); writer.writeEndDocument(); } @Override public LocalTime decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null"); return translateDecodeExceptions(
() -> readDocument(reader, decoderContext, FIELD_DECODERS),
cbartosiak/bson-codecs-jsr310
src/main/java/io/github/cbartosiak/bson/codecs/jsr310/localtime/LocalTimeAsDocumentCodec.java
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value> Value getFieldValue( // Document document, // Object key, // Class<Value> clazz) { // // try { // Value value = document.get(key, clazz); // if (value == null) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is null", key // )); // } // return value; // } // catch (ClassCastException ex) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is not of the type %s", // key, clazz.getName() // ), ex); // } // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static Document readDocument( // BsonReader reader, // DecoderContext decoderContext, // Map<String, Decoder<?>> fieldDecoders) { // // Document document = new Document(); // reader.readStartDocument(); // while (reader.readBsonType() != END_OF_DOCUMENT) { // String fieldName = reader.readName(); // if (fieldDecoders.containsKey(fieldName)) { // document.put( // fieldName, // fieldDecoders // .get(fieldName) // .decode(reader, decoderContext) // ); // } // else { // throw new BsonInvalidOperationException(format( // "The field %s is not expected here", fieldName // )); // } // } // reader.readEndDocument(); // return document; // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // }
import org.bson.codecs.Decoder; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.getFieldValue; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.readDocument; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static java.time.LocalTime.of; import static java.util.Collections.unmodifiableMap; import static java.util.Objects.requireNonNull; import java.time.LocalTime; import java.util.HashMap; import java.util.Map; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec;
fd.put("second", (r, dc) -> r.readInt32()); fd.put("nano", (r, dc) -> r.readInt32()); FIELD_DECODERS = unmodifiableMap(fd); } @Override public void encode( BsonWriter writer, LocalTime value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); writer.writeStartDocument(); writer.writeInt32("hour", value.getHour()); writer.writeInt32("minute", value.getMinute()); writer.writeInt32("second", value.getSecond()); writer.writeInt32("nano", value.getNano()); writer.writeEndDocument(); } @Override public LocalTime decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null"); return translateDecodeExceptions( () -> readDocument(reader, decoderContext, FIELD_DECODERS), val -> of(
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value> Value getFieldValue( // Document document, // Object key, // Class<Value> clazz) { // // try { // Value value = document.get(key, clazz); // if (value == null) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is null", key // )); // } // return value; // } // catch (ClassCastException ex) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is not of the type %s", // key, clazz.getName() // ), ex); // } // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static Document readDocument( // BsonReader reader, // DecoderContext decoderContext, // Map<String, Decoder<?>> fieldDecoders) { // // Document document = new Document(); // reader.readStartDocument(); // while (reader.readBsonType() != END_OF_DOCUMENT) { // String fieldName = reader.readName(); // if (fieldDecoders.containsKey(fieldName)) { // document.put( // fieldName, // fieldDecoders // .get(fieldName) // .decode(reader, decoderContext) // ); // } // else { // throw new BsonInvalidOperationException(format( // "The field %s is not expected here", fieldName // )); // } // } // reader.readEndDocument(); // return document; // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/localtime/LocalTimeAsDocumentCodec.java import org.bson.codecs.Decoder; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.getFieldValue; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.readDocument; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static java.time.LocalTime.of; import static java.util.Collections.unmodifiableMap; import static java.util.Objects.requireNonNull; import java.time.LocalTime; import java.util.HashMap; import java.util.Map; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; fd.put("second", (r, dc) -> r.readInt32()); fd.put("nano", (r, dc) -> r.readInt32()); FIELD_DECODERS = unmodifiableMap(fd); } @Override public void encode( BsonWriter writer, LocalTime value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); writer.writeStartDocument(); writer.writeInt32("hour", value.getHour()); writer.writeInt32("minute", value.getMinute()); writer.writeInt32("second", value.getSecond()); writer.writeInt32("nano", value.getNano()); writer.writeEndDocument(); } @Override public LocalTime decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null"); return translateDecodeExceptions( () -> readDocument(reader, decoderContext, FIELD_DECODERS), val -> of(
getFieldValue(val, "hour", Integer.class),
cbartosiak/bson-codecs-jsr310
src/main/java/io/github/cbartosiak/bson/codecs/jsr310/monthday/MonthDayAsDocumentCodec.java
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value> Value getFieldValue( // Document document, // Object key, // Class<Value> clazz) { // // try { // Value value = document.get(key, clazz); // if (value == null) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is null", key // )); // } // return value; // } // catch (ClassCastException ex) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is not of the type %s", // key, clazz.getName() // ), ex); // } // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static Document readDocument( // BsonReader reader, // DecoderContext decoderContext, // Map<String, Decoder<?>> fieldDecoders) { // // Document document = new Document(); // reader.readStartDocument(); // while (reader.readBsonType() != END_OF_DOCUMENT) { // String fieldName = reader.readName(); // if (fieldDecoders.containsKey(fieldName)) { // document.put( // fieldName, // fieldDecoders // .get(fieldName) // .decode(reader, decoderContext) // ); // } // else { // throw new BsonInvalidOperationException(format( // "The field %s is not expected here", fieldName // )); // } // } // reader.readEndDocument(); // return document; // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // }
import org.bson.codecs.Decoder; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.getFieldValue; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.readDocument; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static java.time.MonthDay.of; import static java.util.Collections.unmodifiableMap; import static java.util.Objects.requireNonNull; import java.time.MonthDay; import java.util.HashMap; import java.util.Map; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec;
/* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.monthday; /** * <p> * Encodes and decodes {@code MonthDay} values to and from * {@code BSON Document}, such as {@code { month: 1, day: 2 }}. * <p> * The values are stored using the following structure: * <ul> * <li>{@code month} (a non-null {@code Int32}); * <li>{@code day} (a non-null {@code Int32}). * </ul> * <p> * This type is <b>immutable</b>. */ public final class MonthDayAsDocumentCodec implements Codec<MonthDay> { private static final Map<String, Decoder<?>> FIELD_DECODERS; static { Map<String, Decoder<?>> fd = new HashMap<>(); fd.put("month", (r, dc) -> r.readInt32()); fd.put("day", (r, dc) -> r.readInt32()); FIELD_DECODERS = unmodifiableMap(fd); } @Override public void encode( BsonWriter writer, MonthDay value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); writer.writeStartDocument(); writer.writeInt32("month", value.getMonthValue()); writer.writeInt32("day", value.getDayOfMonth()); writer.writeEndDocument(); } @Override public MonthDay decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null");
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value> Value getFieldValue( // Document document, // Object key, // Class<Value> clazz) { // // try { // Value value = document.get(key, clazz); // if (value == null) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is null", key // )); // } // return value; // } // catch (ClassCastException ex) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is not of the type %s", // key, clazz.getName() // ), ex); // } // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static Document readDocument( // BsonReader reader, // DecoderContext decoderContext, // Map<String, Decoder<?>> fieldDecoders) { // // Document document = new Document(); // reader.readStartDocument(); // while (reader.readBsonType() != END_OF_DOCUMENT) { // String fieldName = reader.readName(); // if (fieldDecoders.containsKey(fieldName)) { // document.put( // fieldName, // fieldDecoders // .get(fieldName) // .decode(reader, decoderContext) // ); // } // else { // throw new BsonInvalidOperationException(format( // "The field %s is not expected here", fieldName // )); // } // } // reader.readEndDocument(); // return document; // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/monthday/MonthDayAsDocumentCodec.java import org.bson.codecs.Decoder; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.getFieldValue; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.readDocument; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static java.time.MonthDay.of; import static java.util.Collections.unmodifiableMap; import static java.util.Objects.requireNonNull; import java.time.MonthDay; import java.util.HashMap; import java.util.Map; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; /* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.monthday; /** * <p> * Encodes and decodes {@code MonthDay} values to and from * {@code BSON Document}, such as {@code { month: 1, day: 2 }}. * <p> * The values are stored using the following structure: * <ul> * <li>{@code month} (a non-null {@code Int32}); * <li>{@code day} (a non-null {@code Int32}). * </ul> * <p> * This type is <b>immutable</b>. */ public final class MonthDayAsDocumentCodec implements Codec<MonthDay> { private static final Map<String, Decoder<?>> FIELD_DECODERS; static { Map<String, Decoder<?>> fd = new HashMap<>(); fd.put("month", (r, dc) -> r.readInt32()); fd.put("day", (r, dc) -> r.readInt32()); FIELD_DECODERS = unmodifiableMap(fd); } @Override public void encode( BsonWriter writer, MonthDay value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); writer.writeStartDocument(); writer.writeInt32("month", value.getMonthValue()); writer.writeInt32("day", value.getDayOfMonth()); writer.writeEndDocument(); } @Override public MonthDay decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null");
return translateDecodeExceptions(
cbartosiak/bson-codecs-jsr310
src/main/java/io/github/cbartosiak/bson/codecs/jsr310/monthday/MonthDayAsDocumentCodec.java
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value> Value getFieldValue( // Document document, // Object key, // Class<Value> clazz) { // // try { // Value value = document.get(key, clazz); // if (value == null) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is null", key // )); // } // return value; // } // catch (ClassCastException ex) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is not of the type %s", // key, clazz.getName() // ), ex); // } // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static Document readDocument( // BsonReader reader, // DecoderContext decoderContext, // Map<String, Decoder<?>> fieldDecoders) { // // Document document = new Document(); // reader.readStartDocument(); // while (reader.readBsonType() != END_OF_DOCUMENT) { // String fieldName = reader.readName(); // if (fieldDecoders.containsKey(fieldName)) { // document.put( // fieldName, // fieldDecoders // .get(fieldName) // .decode(reader, decoderContext) // ); // } // else { // throw new BsonInvalidOperationException(format( // "The field %s is not expected here", fieldName // )); // } // } // reader.readEndDocument(); // return document; // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // }
import org.bson.codecs.Decoder; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.getFieldValue; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.readDocument; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static java.time.MonthDay.of; import static java.util.Collections.unmodifiableMap; import static java.util.Objects.requireNonNull; import java.time.MonthDay; import java.util.HashMap; import java.util.Map; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec;
/* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.monthday; /** * <p> * Encodes and decodes {@code MonthDay} values to and from * {@code BSON Document}, such as {@code { month: 1, day: 2 }}. * <p> * The values are stored using the following structure: * <ul> * <li>{@code month} (a non-null {@code Int32}); * <li>{@code day} (a non-null {@code Int32}). * </ul> * <p> * This type is <b>immutable</b>. */ public final class MonthDayAsDocumentCodec implements Codec<MonthDay> { private static final Map<String, Decoder<?>> FIELD_DECODERS; static { Map<String, Decoder<?>> fd = new HashMap<>(); fd.put("month", (r, dc) -> r.readInt32()); fd.put("day", (r, dc) -> r.readInt32()); FIELD_DECODERS = unmodifiableMap(fd); } @Override public void encode( BsonWriter writer, MonthDay value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); writer.writeStartDocument(); writer.writeInt32("month", value.getMonthValue()); writer.writeInt32("day", value.getDayOfMonth()); writer.writeEndDocument(); } @Override public MonthDay decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null"); return translateDecodeExceptions(
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value> Value getFieldValue( // Document document, // Object key, // Class<Value> clazz) { // // try { // Value value = document.get(key, clazz); // if (value == null) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is null", key // )); // } // return value; // } // catch (ClassCastException ex) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is not of the type %s", // key, clazz.getName() // ), ex); // } // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static Document readDocument( // BsonReader reader, // DecoderContext decoderContext, // Map<String, Decoder<?>> fieldDecoders) { // // Document document = new Document(); // reader.readStartDocument(); // while (reader.readBsonType() != END_OF_DOCUMENT) { // String fieldName = reader.readName(); // if (fieldDecoders.containsKey(fieldName)) { // document.put( // fieldName, // fieldDecoders // .get(fieldName) // .decode(reader, decoderContext) // ); // } // else { // throw new BsonInvalidOperationException(format( // "The field %s is not expected here", fieldName // )); // } // } // reader.readEndDocument(); // return document; // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/monthday/MonthDayAsDocumentCodec.java import org.bson.codecs.Decoder; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.getFieldValue; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.readDocument; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static java.time.MonthDay.of; import static java.util.Collections.unmodifiableMap; import static java.util.Objects.requireNonNull; import java.time.MonthDay; import java.util.HashMap; import java.util.Map; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; /* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.monthday; /** * <p> * Encodes and decodes {@code MonthDay} values to and from * {@code BSON Document}, such as {@code { month: 1, day: 2 }}. * <p> * The values are stored using the following structure: * <ul> * <li>{@code month} (a non-null {@code Int32}); * <li>{@code day} (a non-null {@code Int32}). * </ul> * <p> * This type is <b>immutable</b>. */ public final class MonthDayAsDocumentCodec implements Codec<MonthDay> { private static final Map<String, Decoder<?>> FIELD_DECODERS; static { Map<String, Decoder<?>> fd = new HashMap<>(); fd.put("month", (r, dc) -> r.readInt32()); fd.put("day", (r, dc) -> r.readInt32()); FIELD_DECODERS = unmodifiableMap(fd); } @Override public void encode( BsonWriter writer, MonthDay value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); writer.writeStartDocument(); writer.writeInt32("month", value.getMonthValue()); writer.writeInt32("day", value.getDayOfMonth()); writer.writeEndDocument(); } @Override public MonthDay decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null"); return translateDecodeExceptions(
() -> readDocument(reader, decoderContext, FIELD_DECODERS),
cbartosiak/bson-codecs-jsr310
src/main/java/io/github/cbartosiak/bson/codecs/jsr310/monthday/MonthDayAsDocumentCodec.java
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value> Value getFieldValue( // Document document, // Object key, // Class<Value> clazz) { // // try { // Value value = document.get(key, clazz); // if (value == null) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is null", key // )); // } // return value; // } // catch (ClassCastException ex) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is not of the type %s", // key, clazz.getName() // ), ex); // } // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static Document readDocument( // BsonReader reader, // DecoderContext decoderContext, // Map<String, Decoder<?>> fieldDecoders) { // // Document document = new Document(); // reader.readStartDocument(); // while (reader.readBsonType() != END_OF_DOCUMENT) { // String fieldName = reader.readName(); // if (fieldDecoders.containsKey(fieldName)) { // document.put( // fieldName, // fieldDecoders // .get(fieldName) // .decode(reader, decoderContext) // ); // } // else { // throw new BsonInvalidOperationException(format( // "The field %s is not expected here", fieldName // )); // } // } // reader.readEndDocument(); // return document; // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // }
import org.bson.codecs.Decoder; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.getFieldValue; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.readDocument; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static java.time.MonthDay.of; import static java.util.Collections.unmodifiableMap; import static java.util.Objects.requireNonNull; import java.time.MonthDay; import java.util.HashMap; import java.util.Map; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec;
/* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.monthday; /** * <p> * Encodes and decodes {@code MonthDay} values to and from * {@code BSON Document}, such as {@code { month: 1, day: 2 }}. * <p> * The values are stored using the following structure: * <ul> * <li>{@code month} (a non-null {@code Int32}); * <li>{@code day} (a non-null {@code Int32}). * </ul> * <p> * This type is <b>immutable</b>. */ public final class MonthDayAsDocumentCodec implements Codec<MonthDay> { private static final Map<String, Decoder<?>> FIELD_DECODERS; static { Map<String, Decoder<?>> fd = new HashMap<>(); fd.put("month", (r, dc) -> r.readInt32()); fd.put("day", (r, dc) -> r.readInt32()); FIELD_DECODERS = unmodifiableMap(fd); } @Override public void encode( BsonWriter writer, MonthDay value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); writer.writeStartDocument(); writer.writeInt32("month", value.getMonthValue()); writer.writeInt32("day", value.getDayOfMonth()); writer.writeEndDocument(); } @Override public MonthDay decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null"); return translateDecodeExceptions( () -> readDocument(reader, decoderContext, FIELD_DECODERS), val -> of(
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value> Value getFieldValue( // Document document, // Object key, // Class<Value> clazz) { // // try { // Value value = document.get(key, clazz); // if (value == null) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is null", key // )); // } // return value; // } // catch (ClassCastException ex) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is not of the type %s", // key, clazz.getName() // ), ex); // } // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static Document readDocument( // BsonReader reader, // DecoderContext decoderContext, // Map<String, Decoder<?>> fieldDecoders) { // // Document document = new Document(); // reader.readStartDocument(); // while (reader.readBsonType() != END_OF_DOCUMENT) { // String fieldName = reader.readName(); // if (fieldDecoders.containsKey(fieldName)) { // document.put( // fieldName, // fieldDecoders // .get(fieldName) // .decode(reader, decoderContext) // ); // } // else { // throw new BsonInvalidOperationException(format( // "The field %s is not expected here", fieldName // )); // } // } // reader.readEndDocument(); // return document; // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/monthday/MonthDayAsDocumentCodec.java import org.bson.codecs.Decoder; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.getFieldValue; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.readDocument; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static java.time.MonthDay.of; import static java.util.Collections.unmodifiableMap; import static java.util.Objects.requireNonNull; import java.time.MonthDay; import java.util.HashMap; import java.util.Map; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; /* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.monthday; /** * <p> * Encodes and decodes {@code MonthDay} values to and from * {@code BSON Document}, such as {@code { month: 1, day: 2 }}. * <p> * The values are stored using the following structure: * <ul> * <li>{@code month} (a non-null {@code Int32}); * <li>{@code day} (a non-null {@code Int32}). * </ul> * <p> * This type is <b>immutable</b>. */ public final class MonthDayAsDocumentCodec implements Codec<MonthDay> { private static final Map<String, Decoder<?>> FIELD_DECODERS; static { Map<String, Decoder<?>> fd = new HashMap<>(); fd.put("month", (r, dc) -> r.readInt32()); fd.put("day", (r, dc) -> r.readInt32()); FIELD_DECODERS = unmodifiableMap(fd); } @Override public void encode( BsonWriter writer, MonthDay value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); writer.writeStartDocument(); writer.writeInt32("month", value.getMonthValue()); writer.writeInt32("day", value.getDayOfMonth()); writer.writeEndDocument(); } @Override public MonthDay decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null"); return translateDecodeExceptions( () -> readDocument(reader, decoderContext, FIELD_DECODERS), val -> of(
getFieldValue(val, "month", Integer.class),
cbartosiak/bson-codecs-jsr310
src/main/java/io/github/cbartosiak/bson/codecs/jsr310/localdate/LocalDateAsStringCodec.java
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // }
import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static java.util.Objects.requireNonNull; import java.time.LocalDate; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext;
/* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.localdate; /** * <p> * Encodes and decodes {@code LocalDate} values to and from * {@code BSON String}, such as {@code 2018-01-02}. * <p> * The values are stored as {@code ISO-8601} formatted strings * (see {@link LocalDate#toString()}). * <p> * This type is <b>immutable</b>. */ public final class LocalDateAsStringCodec implements Codec<LocalDate> { @Override public void encode( BsonWriter writer, LocalDate value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); writer.writeString(value.toString()); } @Override public LocalDate decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null");
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/localdate/LocalDateAsStringCodec.java import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static java.util.Objects.requireNonNull; import java.time.LocalDate; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext; /* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.localdate; /** * <p> * Encodes and decodes {@code LocalDate} values to and from * {@code BSON String}, such as {@code 2018-01-02}. * <p> * The values are stored as {@code ISO-8601} formatted strings * (see {@link LocalDate#toString()}). * <p> * This type is <b>immutable</b>. */ public final class LocalDateAsStringCodec implements Codec<LocalDate> { @Override public void encode( BsonWriter writer, LocalDate value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); writer.writeString(value.toString()); } @Override public LocalDate decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null");
return translateDecodeExceptions(
cbartosiak/bson-codecs-jsr310
src/main/java/io/github/cbartosiak/bson/codecs/jsr310/localdate/LocalDateAsDocumentCodec.java
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value> Value getFieldValue( // Document document, // Object key, // Class<Value> clazz) { // // try { // Value value = document.get(key, clazz); // if (value == null) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is null", key // )); // } // return value; // } // catch (ClassCastException ex) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is not of the type %s", // key, clazz.getName() // ), ex); // } // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static Document readDocument( // BsonReader reader, // DecoderContext decoderContext, // Map<String, Decoder<?>> fieldDecoders) { // // Document document = new Document(); // reader.readStartDocument(); // while (reader.readBsonType() != END_OF_DOCUMENT) { // String fieldName = reader.readName(); // if (fieldDecoders.containsKey(fieldName)) { // document.put( // fieldName, // fieldDecoders // .get(fieldName) // .decode(reader, decoderContext) // ); // } // else { // throw new BsonInvalidOperationException(format( // "The field %s is not expected here", fieldName // )); // } // } // reader.readEndDocument(); // return document; // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // }
import org.bson.codecs.Decoder; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.getFieldValue; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.readDocument; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static java.time.LocalDate.of; import static java.util.Collections.unmodifiableMap; import static java.util.Objects.requireNonNull; import java.time.LocalDate; import java.util.HashMap; import java.util.Map; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec;
/* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.localdate; /** * <p> * Encodes and decodes {@code LocalDate} values to and from * {@code BSON Document}, such as {@code { year: 2018, month: 1, day: 2 }}. * <p> * The values are stored using the following structure: * <ul> * <li>{@code year} (a non-null {@code Int32}); * <li>{@code month} (a non-null {@code Int32}); * <li>{@code day} (a non-null {@code Int32}). * </ul> * <p> * This type is <b>immutable</b>. */ public final class LocalDateAsDocumentCodec implements Codec<LocalDate> { private static final Map<String, Decoder<?>> FIELD_DECODERS; static { Map<String, Decoder<?>> fd = new HashMap<>(); fd.put("year", (r, dc) -> r.readInt32()); fd.put("month", (r, dc) -> r.readInt32()); fd.put("day", (r, dc) -> r.readInt32()); FIELD_DECODERS = unmodifiableMap(fd); } @Override public void encode( BsonWriter writer, LocalDate value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); writer.writeStartDocument(); writer.writeInt32("year", value.getYear()); writer.writeInt32("month", value.getMonthValue()); writer.writeInt32("day", value.getDayOfMonth()); writer.writeEndDocument(); } @Override public LocalDate decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null");
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value> Value getFieldValue( // Document document, // Object key, // Class<Value> clazz) { // // try { // Value value = document.get(key, clazz); // if (value == null) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is null", key // )); // } // return value; // } // catch (ClassCastException ex) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is not of the type %s", // key, clazz.getName() // ), ex); // } // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static Document readDocument( // BsonReader reader, // DecoderContext decoderContext, // Map<String, Decoder<?>> fieldDecoders) { // // Document document = new Document(); // reader.readStartDocument(); // while (reader.readBsonType() != END_OF_DOCUMENT) { // String fieldName = reader.readName(); // if (fieldDecoders.containsKey(fieldName)) { // document.put( // fieldName, // fieldDecoders // .get(fieldName) // .decode(reader, decoderContext) // ); // } // else { // throw new BsonInvalidOperationException(format( // "The field %s is not expected here", fieldName // )); // } // } // reader.readEndDocument(); // return document; // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/localdate/LocalDateAsDocumentCodec.java import org.bson.codecs.Decoder; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.getFieldValue; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.readDocument; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static java.time.LocalDate.of; import static java.util.Collections.unmodifiableMap; import static java.util.Objects.requireNonNull; import java.time.LocalDate; import java.util.HashMap; import java.util.Map; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; /* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.localdate; /** * <p> * Encodes and decodes {@code LocalDate} values to and from * {@code BSON Document}, such as {@code { year: 2018, month: 1, day: 2 }}. * <p> * The values are stored using the following structure: * <ul> * <li>{@code year} (a non-null {@code Int32}); * <li>{@code month} (a non-null {@code Int32}); * <li>{@code day} (a non-null {@code Int32}). * </ul> * <p> * This type is <b>immutable</b>. */ public final class LocalDateAsDocumentCodec implements Codec<LocalDate> { private static final Map<String, Decoder<?>> FIELD_DECODERS; static { Map<String, Decoder<?>> fd = new HashMap<>(); fd.put("year", (r, dc) -> r.readInt32()); fd.put("month", (r, dc) -> r.readInt32()); fd.put("day", (r, dc) -> r.readInt32()); FIELD_DECODERS = unmodifiableMap(fd); } @Override public void encode( BsonWriter writer, LocalDate value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); writer.writeStartDocument(); writer.writeInt32("year", value.getYear()); writer.writeInt32("month", value.getMonthValue()); writer.writeInt32("day", value.getDayOfMonth()); writer.writeEndDocument(); } @Override public LocalDate decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null");
return translateDecodeExceptions(
cbartosiak/bson-codecs-jsr310
src/main/java/io/github/cbartosiak/bson/codecs/jsr310/localdate/LocalDateAsDocumentCodec.java
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value> Value getFieldValue( // Document document, // Object key, // Class<Value> clazz) { // // try { // Value value = document.get(key, clazz); // if (value == null) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is null", key // )); // } // return value; // } // catch (ClassCastException ex) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is not of the type %s", // key, clazz.getName() // ), ex); // } // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static Document readDocument( // BsonReader reader, // DecoderContext decoderContext, // Map<String, Decoder<?>> fieldDecoders) { // // Document document = new Document(); // reader.readStartDocument(); // while (reader.readBsonType() != END_OF_DOCUMENT) { // String fieldName = reader.readName(); // if (fieldDecoders.containsKey(fieldName)) { // document.put( // fieldName, // fieldDecoders // .get(fieldName) // .decode(reader, decoderContext) // ); // } // else { // throw new BsonInvalidOperationException(format( // "The field %s is not expected here", fieldName // )); // } // } // reader.readEndDocument(); // return document; // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // }
import org.bson.codecs.Decoder; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.getFieldValue; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.readDocument; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static java.time.LocalDate.of; import static java.util.Collections.unmodifiableMap; import static java.util.Objects.requireNonNull; import java.time.LocalDate; import java.util.HashMap; import java.util.Map; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec;
/* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.localdate; /** * <p> * Encodes and decodes {@code LocalDate} values to and from * {@code BSON Document}, such as {@code { year: 2018, month: 1, day: 2 }}. * <p> * The values are stored using the following structure: * <ul> * <li>{@code year} (a non-null {@code Int32}); * <li>{@code month} (a non-null {@code Int32}); * <li>{@code day} (a non-null {@code Int32}). * </ul> * <p> * This type is <b>immutable</b>. */ public final class LocalDateAsDocumentCodec implements Codec<LocalDate> { private static final Map<String, Decoder<?>> FIELD_DECODERS; static { Map<String, Decoder<?>> fd = new HashMap<>(); fd.put("year", (r, dc) -> r.readInt32()); fd.put("month", (r, dc) -> r.readInt32()); fd.put("day", (r, dc) -> r.readInt32()); FIELD_DECODERS = unmodifiableMap(fd); } @Override public void encode( BsonWriter writer, LocalDate value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); writer.writeStartDocument(); writer.writeInt32("year", value.getYear()); writer.writeInt32("month", value.getMonthValue()); writer.writeInt32("day", value.getDayOfMonth()); writer.writeEndDocument(); } @Override public LocalDate decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null"); return translateDecodeExceptions(
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value> Value getFieldValue( // Document document, // Object key, // Class<Value> clazz) { // // try { // Value value = document.get(key, clazz); // if (value == null) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is null", key // )); // } // return value; // } // catch (ClassCastException ex) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is not of the type %s", // key, clazz.getName() // ), ex); // } // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static Document readDocument( // BsonReader reader, // DecoderContext decoderContext, // Map<String, Decoder<?>> fieldDecoders) { // // Document document = new Document(); // reader.readStartDocument(); // while (reader.readBsonType() != END_OF_DOCUMENT) { // String fieldName = reader.readName(); // if (fieldDecoders.containsKey(fieldName)) { // document.put( // fieldName, // fieldDecoders // .get(fieldName) // .decode(reader, decoderContext) // ); // } // else { // throw new BsonInvalidOperationException(format( // "The field %s is not expected here", fieldName // )); // } // } // reader.readEndDocument(); // return document; // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/localdate/LocalDateAsDocumentCodec.java import org.bson.codecs.Decoder; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.getFieldValue; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.readDocument; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static java.time.LocalDate.of; import static java.util.Collections.unmodifiableMap; import static java.util.Objects.requireNonNull; import java.time.LocalDate; import java.util.HashMap; import java.util.Map; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; /* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.localdate; /** * <p> * Encodes and decodes {@code LocalDate} values to and from * {@code BSON Document}, such as {@code { year: 2018, month: 1, day: 2 }}. * <p> * The values are stored using the following structure: * <ul> * <li>{@code year} (a non-null {@code Int32}); * <li>{@code month} (a non-null {@code Int32}); * <li>{@code day} (a non-null {@code Int32}). * </ul> * <p> * This type is <b>immutable</b>. */ public final class LocalDateAsDocumentCodec implements Codec<LocalDate> { private static final Map<String, Decoder<?>> FIELD_DECODERS; static { Map<String, Decoder<?>> fd = new HashMap<>(); fd.put("year", (r, dc) -> r.readInt32()); fd.put("month", (r, dc) -> r.readInt32()); fd.put("day", (r, dc) -> r.readInt32()); FIELD_DECODERS = unmodifiableMap(fd); } @Override public void encode( BsonWriter writer, LocalDate value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); writer.writeStartDocument(); writer.writeInt32("year", value.getYear()); writer.writeInt32("month", value.getMonthValue()); writer.writeInt32("day", value.getDayOfMonth()); writer.writeEndDocument(); } @Override public LocalDate decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null"); return translateDecodeExceptions(
() -> readDocument(reader, decoderContext, FIELD_DECODERS),
cbartosiak/bson-codecs-jsr310
src/main/java/io/github/cbartosiak/bson/codecs/jsr310/localdate/LocalDateAsDocumentCodec.java
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value> Value getFieldValue( // Document document, // Object key, // Class<Value> clazz) { // // try { // Value value = document.get(key, clazz); // if (value == null) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is null", key // )); // } // return value; // } // catch (ClassCastException ex) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is not of the type %s", // key, clazz.getName() // ), ex); // } // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static Document readDocument( // BsonReader reader, // DecoderContext decoderContext, // Map<String, Decoder<?>> fieldDecoders) { // // Document document = new Document(); // reader.readStartDocument(); // while (reader.readBsonType() != END_OF_DOCUMENT) { // String fieldName = reader.readName(); // if (fieldDecoders.containsKey(fieldName)) { // document.put( // fieldName, // fieldDecoders // .get(fieldName) // .decode(reader, decoderContext) // ); // } // else { // throw new BsonInvalidOperationException(format( // "The field %s is not expected here", fieldName // )); // } // } // reader.readEndDocument(); // return document; // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // }
import org.bson.codecs.Decoder; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.getFieldValue; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.readDocument; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static java.time.LocalDate.of; import static java.util.Collections.unmodifiableMap; import static java.util.Objects.requireNonNull; import java.time.LocalDate; import java.util.HashMap; import java.util.Map; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec;
fd.put("year", (r, dc) -> r.readInt32()); fd.put("month", (r, dc) -> r.readInt32()); fd.put("day", (r, dc) -> r.readInt32()); FIELD_DECODERS = unmodifiableMap(fd); } @Override public void encode( BsonWriter writer, LocalDate value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); writer.writeStartDocument(); writer.writeInt32("year", value.getYear()); writer.writeInt32("month", value.getMonthValue()); writer.writeInt32("day", value.getDayOfMonth()); writer.writeEndDocument(); } @Override public LocalDate decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null"); return translateDecodeExceptions( () -> readDocument(reader, decoderContext, FIELD_DECODERS), val -> of(
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value> Value getFieldValue( // Document document, // Object key, // Class<Value> clazz) { // // try { // Value value = document.get(key, clazz); // if (value == null) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is null", key // )); // } // return value; // } // catch (ClassCastException ex) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is not of the type %s", // key, clazz.getName() // ), ex); // } // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static Document readDocument( // BsonReader reader, // DecoderContext decoderContext, // Map<String, Decoder<?>> fieldDecoders) { // // Document document = new Document(); // reader.readStartDocument(); // while (reader.readBsonType() != END_OF_DOCUMENT) { // String fieldName = reader.readName(); // if (fieldDecoders.containsKey(fieldName)) { // document.put( // fieldName, // fieldDecoders // .get(fieldName) // .decode(reader, decoderContext) // ); // } // else { // throw new BsonInvalidOperationException(format( // "The field %s is not expected here", fieldName // )); // } // } // reader.readEndDocument(); // return document; // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/localdate/LocalDateAsDocumentCodec.java import org.bson.codecs.Decoder; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.getFieldValue; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.readDocument; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static java.time.LocalDate.of; import static java.util.Collections.unmodifiableMap; import static java.util.Objects.requireNonNull; import java.time.LocalDate; import java.util.HashMap; import java.util.Map; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; fd.put("year", (r, dc) -> r.readInt32()); fd.put("month", (r, dc) -> r.readInt32()); fd.put("day", (r, dc) -> r.readInt32()); FIELD_DECODERS = unmodifiableMap(fd); } @Override public void encode( BsonWriter writer, LocalDate value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); writer.writeStartDocument(); writer.writeInt32("year", value.getYear()); writer.writeInt32("month", value.getMonthValue()); writer.writeInt32("day", value.getDayOfMonth()); writer.writeEndDocument(); } @Override public LocalDate decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null"); return translateDecodeExceptions( () -> readDocument(reader, decoderContext, FIELD_DECODERS), val -> of(
getFieldValue(val, "year", Integer.class),
cbartosiak/bson-codecs-jsr310
src/main/java/io/github/cbartosiak/bson/codecs/jsr310/year/YearAsInt32Codec.java
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // }
import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static java.util.Objects.requireNonNull; import java.time.Year; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext;
/* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.year; /** * <p> * Encodes and decodes {@code Year} values to and from * {@code BSON Int32}, such as {@code 2018}. * <p> * The values are stored as ISO proleptic year integers * (see {@link Year#getValue()}). * <p> * This type is <b>immutable</b>. */ public final class YearAsInt32Codec implements Codec<Year> { @Override public void encode( BsonWriter writer, Year value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); writer.writeInt32(value.getValue()); } @Override public Year decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null");
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/year/YearAsInt32Codec.java import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static java.util.Objects.requireNonNull; import java.time.Year; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext; /* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.year; /** * <p> * Encodes and decodes {@code Year} values to and from * {@code BSON Int32}, such as {@code 2018}. * <p> * The values are stored as ISO proleptic year integers * (see {@link Year#getValue()}). * <p> * This type is <b>immutable</b>. */ public final class YearAsInt32Codec implements Codec<Year> { @Override public void encode( BsonWriter writer, Year value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); writer.writeInt32(value.getValue()); } @Override public Year decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null");
return translateDecodeExceptions(
cbartosiak/bson-codecs-jsr310
src/main/java/io/github/cbartosiak/bson/codecs/jsr310/localtime/LocalTimeAsDateTimeCodec.java
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value> void translateEncodeExceptions( // Supplier<Value> valueSupplier, // Consumer<Value> valueConsumer) { // // Value value = valueSupplier.get(); // try { // valueConsumer.accept(value); // } // catch (ArithmeticException | // DateTimeException | // NumberFormatException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // }
import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateEncodeExceptions; import static java.time.Instant.ofEpochMilli; import static java.time.LocalDate.ofEpochDay; import static java.time.ZoneOffset.UTC; import static java.util.Objects.requireNonNull; import java.time.LocalTime; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext;
/* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.localtime; /** * <p> * Encodes and decodes {@code LocalTime} values to and from * {@code BSON DateTime}. * <p> * Note the following implementation details: * <ul> * <li>the date part is considered Unix epoch day (1970-01-01); * <li>the zone offset part is considered UTC; * <li>the nanoseconds precision is lost. * </ul> * <p> * This type is <b>immutable</b>. */ public final class LocalTimeAsDateTimeCodec implements Codec<LocalTime> { @Override public void encode( BsonWriter writer, LocalTime value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null");
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value> void translateEncodeExceptions( // Supplier<Value> valueSupplier, // Consumer<Value> valueConsumer) { // // Value value = valueSupplier.get(); // try { // valueConsumer.accept(value); // } // catch (ArithmeticException | // DateTimeException | // NumberFormatException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/localtime/LocalTimeAsDateTimeCodec.java import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateEncodeExceptions; import static java.time.Instant.ofEpochMilli; import static java.time.LocalDate.ofEpochDay; import static java.time.ZoneOffset.UTC; import static java.util.Objects.requireNonNull; import java.time.LocalTime; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext; /* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.localtime; /** * <p> * Encodes and decodes {@code LocalTime} values to and from * {@code BSON DateTime}. * <p> * Note the following implementation details: * <ul> * <li>the date part is considered Unix epoch day (1970-01-01); * <li>the zone offset part is considered UTC; * <li>the nanoseconds precision is lost. * </ul> * <p> * This type is <b>immutable</b>. */ public final class LocalTimeAsDateTimeCodec implements Codec<LocalTime> { @Override public void encode( BsonWriter writer, LocalTime value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null");
translateEncodeExceptions(
cbartosiak/bson-codecs-jsr310
src/main/java/io/github/cbartosiak/bson/codecs/jsr310/localtime/LocalTimeAsDateTimeCodec.java
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value> void translateEncodeExceptions( // Supplier<Value> valueSupplier, // Consumer<Value> valueConsumer) { // // Value value = valueSupplier.get(); // try { // valueConsumer.accept(value); // } // catch (ArithmeticException | // DateTimeException | // NumberFormatException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // }
import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateEncodeExceptions; import static java.time.Instant.ofEpochMilli; import static java.time.LocalDate.ofEpochDay; import static java.time.ZoneOffset.UTC; import static java.util.Objects.requireNonNull; import java.time.LocalTime; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext;
/* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.localtime; /** * <p> * Encodes and decodes {@code LocalTime} values to and from * {@code BSON DateTime}. * <p> * Note the following implementation details: * <ul> * <li>the date part is considered Unix epoch day (1970-01-01); * <li>the zone offset part is considered UTC; * <li>the nanoseconds precision is lost. * </ul> * <p> * This type is <b>immutable</b>. */ public final class LocalTimeAsDateTimeCodec implements Codec<LocalTime> { @Override public void encode( BsonWriter writer, LocalTime value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); translateEncodeExceptions( () -> value, val -> writer.writeDateTime( val.atDate(ofEpochDay(0L)) .toInstant(UTC) .toEpochMilli() ) ); } @Override public LocalTime decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null");
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value> void translateEncodeExceptions( // Supplier<Value> valueSupplier, // Consumer<Value> valueConsumer) { // // Value value = valueSupplier.get(); // try { // valueConsumer.accept(value); // } // catch (ArithmeticException | // DateTimeException | // NumberFormatException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/localtime/LocalTimeAsDateTimeCodec.java import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateEncodeExceptions; import static java.time.Instant.ofEpochMilli; import static java.time.LocalDate.ofEpochDay; import static java.time.ZoneOffset.UTC; import static java.util.Objects.requireNonNull; import java.time.LocalTime; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext; /* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.localtime; /** * <p> * Encodes and decodes {@code LocalTime} values to and from * {@code BSON DateTime}. * <p> * Note the following implementation details: * <ul> * <li>the date part is considered Unix epoch day (1970-01-01); * <li>the zone offset part is considered UTC; * <li>the nanoseconds precision is lost. * </ul> * <p> * This type is <b>immutable</b>. */ public final class LocalTimeAsDateTimeCodec implements Codec<LocalTime> { @Override public void encode( BsonWriter writer, LocalTime value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); translateEncodeExceptions( () -> value, val -> writer.writeDateTime( val.atDate(ofEpochDay(0L)) .toInstant(UTC) .toEpochMilli() ) ); } @Override public LocalTime decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null");
return translateDecodeExceptions(
cbartosiak/bson-codecs-jsr310
src/main/java/io/github/cbartosiak/bson/codecs/jsr310/dayofweek/DayOfWeekAsStringCodec.java
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // }
import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static java.util.Objects.requireNonNull; import java.time.DayOfWeek; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext;
/* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.dayofweek; /** * <p> * Encodes and decodes {@code DayOfWeek} values to and from * {@code BSON String}, such as {@code TUESDAY}. * <p> * The values are stored as enum constant names * (see {@link DayOfWeek#name()}). * <p> * This type is <b>immutable</b>. */ public final class DayOfWeekAsStringCodec implements Codec<DayOfWeek> { @Override public void encode( BsonWriter writer, DayOfWeek value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); writer.writeString(value.name()); } @Override public DayOfWeek decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null");
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/dayofweek/DayOfWeekAsStringCodec.java import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static java.util.Objects.requireNonNull; import java.time.DayOfWeek; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext; /* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.dayofweek; /** * <p> * Encodes and decodes {@code DayOfWeek} values to and from * {@code BSON String}, such as {@code TUESDAY}. * <p> * The values are stored as enum constant names * (see {@link DayOfWeek#name()}). * <p> * This type is <b>immutable</b>. */ public final class DayOfWeekAsStringCodec implements Codec<DayOfWeek> { @Override public void encode( BsonWriter writer, DayOfWeek value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); writer.writeString(value.name()); } @Override public DayOfWeek decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null");
return translateDecodeExceptions(
cbartosiak/bson-codecs-jsr310
src/main/java/io/github/cbartosiak/bson/codecs/jsr310/yearmonth/YearMonthAsDecimal128Codec.java
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value> void translateEncodeExceptions( // Supplier<Value> valueSupplier, // Consumer<Value> valueConsumer) { // // Value value = valueSupplier.get(); // try { // valueConsumer.accept(value); // } // catch (ArithmeticException | // DateTimeException | // NumberFormatException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // }
import org.bson.codecs.EncoderContext; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateEncodeExceptions; import static java.lang.String.format; import static java.time.YearMonth.of; import static java.util.Objects.requireNonNull; import static org.bson.types.Decimal128.parse; import java.math.BigDecimal; import java.time.YearMonth; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; import org.bson.codecs.DecoderContext;
/* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.yearmonth; /** * <p> * Encodes and decodes {@code YearMonth} values to and from * {@code BSON Decimal128}, such as {@code 2018.01}. * <p> * The values are stored using the following format: {@code %d.%02d} * <ul> * <li>the first part represents a year; * <li>the latter part represents a month of this year. * </ul> * <p> * This type is <b>immutable</b>. */ public final class YearMonthAsDecimal128Codec implements Codec<YearMonth> { @Override public void encode( BsonWriter writer, YearMonth value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null");
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value> void translateEncodeExceptions( // Supplier<Value> valueSupplier, // Consumer<Value> valueConsumer) { // // Value value = valueSupplier.get(); // try { // valueConsumer.accept(value); // } // catch (ArithmeticException | // DateTimeException | // NumberFormatException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/yearmonth/YearMonthAsDecimal128Codec.java import org.bson.codecs.EncoderContext; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateEncodeExceptions; import static java.lang.String.format; import static java.time.YearMonth.of; import static java.util.Objects.requireNonNull; import static org.bson.types.Decimal128.parse; import java.math.BigDecimal; import java.time.YearMonth; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; import org.bson.codecs.DecoderContext; /* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.yearmonth; /** * <p> * Encodes and decodes {@code YearMonth} values to and from * {@code BSON Decimal128}, such as {@code 2018.01}. * <p> * The values are stored using the following format: {@code %d.%02d} * <ul> * <li>the first part represents a year; * <li>the latter part represents a month of this year. * </ul> * <p> * This type is <b>immutable</b>. */ public final class YearMonthAsDecimal128Codec implements Codec<YearMonth> { @Override public void encode( BsonWriter writer, YearMonth value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null");
translateEncodeExceptions(
cbartosiak/bson-codecs-jsr310
src/main/java/io/github/cbartosiak/bson/codecs/jsr310/yearmonth/YearMonthAsDecimal128Codec.java
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value> void translateEncodeExceptions( // Supplier<Value> valueSupplier, // Consumer<Value> valueConsumer) { // // Value value = valueSupplier.get(); // try { // valueConsumer.accept(value); // } // catch (ArithmeticException | // DateTimeException | // NumberFormatException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // }
import org.bson.codecs.EncoderContext; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateEncodeExceptions; import static java.lang.String.format; import static java.time.YearMonth.of; import static java.util.Objects.requireNonNull; import static org.bson.types.Decimal128.parse; import java.math.BigDecimal; import java.time.YearMonth; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; import org.bson.codecs.DecoderContext;
/* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.yearmonth; /** * <p> * Encodes and decodes {@code YearMonth} values to and from * {@code BSON Decimal128}, such as {@code 2018.01}. * <p> * The values are stored using the following format: {@code %d.%02d} * <ul> * <li>the first part represents a year; * <li>the latter part represents a month of this year. * </ul> * <p> * This type is <b>immutable</b>. */ public final class YearMonthAsDecimal128Codec implements Codec<YearMonth> { @Override public void encode( BsonWriter writer, YearMonth value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); translateEncodeExceptions( () -> value, val -> writer.writeDecimal128(parse(format( "%d.%02d", val.getYear(), val.getMonthValue() ))) ); } @Override public YearMonth decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null");
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value> void translateEncodeExceptions( // Supplier<Value> valueSupplier, // Consumer<Value> valueConsumer) { // // Value value = valueSupplier.get(); // try { // valueConsumer.accept(value); // } // catch (ArithmeticException | // DateTimeException | // NumberFormatException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/yearmonth/YearMonthAsDecimal128Codec.java import org.bson.codecs.EncoderContext; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateEncodeExceptions; import static java.lang.String.format; import static java.time.YearMonth.of; import static java.util.Objects.requireNonNull; import static org.bson.types.Decimal128.parse; import java.math.BigDecimal; import java.time.YearMonth; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; import org.bson.codecs.DecoderContext; /* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.yearmonth; /** * <p> * Encodes and decodes {@code YearMonth} values to and from * {@code BSON Decimal128}, such as {@code 2018.01}. * <p> * The values are stored using the following format: {@code %d.%02d} * <ul> * <li>the first part represents a year; * <li>the latter part represents a month of this year. * </ul> * <p> * This type is <b>immutable</b>. */ public final class YearMonthAsDecimal128Codec implements Codec<YearMonth> { @Override public void encode( BsonWriter writer, YearMonth value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); translateEncodeExceptions( () -> value, val -> writer.writeDecimal128(parse(format( "%d.%02d", val.getYear(), val.getMonthValue() ))) ); } @Override public YearMonth decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null");
return translateDecodeExceptions(
cbartosiak/bson-codecs-jsr310
src/main/java/io/github/cbartosiak/bson/codecs/jsr310/dayofweek/DayOfWeekAsInt32Codec.java
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // }
import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static java.util.Objects.requireNonNull; import java.time.DayOfWeek; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext;
/* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.dayofweek; /** * <p> * Encodes and decodes {@code DayOfWeek} values to and from * {@code BSON Int32}, such as {@code 2}. * <p> * The values are stored as {@code ISO-8601} integers * (see {@link DayOfWeek#getValue()}). * <p> * This type is <b>immutable</b>. */ public final class DayOfWeekAsInt32Codec implements Codec<DayOfWeek> { @Override public void encode( BsonWriter writer, DayOfWeek value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); writer.writeInt32(value.getValue()); } @Override public DayOfWeek decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null");
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/dayofweek/DayOfWeekAsInt32Codec.java import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static java.util.Objects.requireNonNull; import java.time.DayOfWeek; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext; /* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.dayofweek; /** * <p> * Encodes and decodes {@code DayOfWeek} values to and from * {@code BSON Int32}, such as {@code 2}. * <p> * The values are stored as {@code ISO-8601} integers * (see {@link DayOfWeek#getValue()}). * <p> * This type is <b>immutable</b>. */ public final class DayOfWeekAsInt32Codec implements Codec<DayOfWeek> { @Override public void encode( BsonWriter writer, DayOfWeek value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); writer.writeInt32(value.getValue()); } @Override public DayOfWeek decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null");
return translateDecodeExceptions(
cbartosiak/bson-codecs-jsr310
src/main/java/io/github/cbartosiak/bson/codecs/jsr310/localdatetime/LocalDateTimeAsDateTimeCodec.java
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value> void translateEncodeExceptions( // Supplier<Value> valueSupplier, // Consumer<Value> valueConsumer) { // // Value value = valueSupplier.get(); // try { // valueConsumer.accept(value); // } // catch (ArithmeticException | // DateTimeException | // NumberFormatException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // }
import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateEncodeExceptions; import static java.time.Instant.ofEpochMilli; import static java.time.ZoneOffset.UTC; import static java.util.Objects.requireNonNull; import java.time.LocalDateTime; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext;
/* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.localdatetime; /** * <p> * Encodes and decodes {@code LocalDateTime} values to and from * {@code BSON DateTime}. * <p> * Note the following implementation details: * <ul> * <li>the zone offset part is considered UTC; * <li>the nanoseconds precision is lost. * </ul> * <p> * This type is <b>immutable</b>. */ public final class LocalDateTimeAsDateTimeCodec implements Codec<LocalDateTime> { @Override public void encode( BsonWriter writer, LocalDateTime value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null");
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value> void translateEncodeExceptions( // Supplier<Value> valueSupplier, // Consumer<Value> valueConsumer) { // // Value value = valueSupplier.get(); // try { // valueConsumer.accept(value); // } // catch (ArithmeticException | // DateTimeException | // NumberFormatException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/localdatetime/LocalDateTimeAsDateTimeCodec.java import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateEncodeExceptions; import static java.time.Instant.ofEpochMilli; import static java.time.ZoneOffset.UTC; import static java.util.Objects.requireNonNull; import java.time.LocalDateTime; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext; /* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.localdatetime; /** * <p> * Encodes and decodes {@code LocalDateTime} values to and from * {@code BSON DateTime}. * <p> * Note the following implementation details: * <ul> * <li>the zone offset part is considered UTC; * <li>the nanoseconds precision is lost. * </ul> * <p> * This type is <b>immutable</b>. */ public final class LocalDateTimeAsDateTimeCodec implements Codec<LocalDateTime> { @Override public void encode( BsonWriter writer, LocalDateTime value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null");
translateEncodeExceptions(
cbartosiak/bson-codecs-jsr310
src/main/java/io/github/cbartosiak/bson/codecs/jsr310/localdatetime/LocalDateTimeAsDateTimeCodec.java
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value> void translateEncodeExceptions( // Supplier<Value> valueSupplier, // Consumer<Value> valueConsumer) { // // Value value = valueSupplier.get(); // try { // valueConsumer.accept(value); // } // catch (ArithmeticException | // DateTimeException | // NumberFormatException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // }
import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateEncodeExceptions; import static java.time.Instant.ofEpochMilli; import static java.time.ZoneOffset.UTC; import static java.util.Objects.requireNonNull; import java.time.LocalDateTime; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext;
/* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.localdatetime; /** * <p> * Encodes and decodes {@code LocalDateTime} values to and from * {@code BSON DateTime}. * <p> * Note the following implementation details: * <ul> * <li>the zone offset part is considered UTC; * <li>the nanoseconds precision is lost. * </ul> * <p> * This type is <b>immutable</b>. */ public final class LocalDateTimeAsDateTimeCodec implements Codec<LocalDateTime> { @Override public void encode( BsonWriter writer, LocalDateTime value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); translateEncodeExceptions( () -> value, val -> writer.writeDateTime( val.toInstant(UTC) .toEpochMilli() ) ); } @Override public LocalDateTime decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null");
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value> void translateEncodeExceptions( // Supplier<Value> valueSupplier, // Consumer<Value> valueConsumer) { // // Value value = valueSupplier.get(); // try { // valueConsumer.accept(value); // } // catch (ArithmeticException | // DateTimeException | // NumberFormatException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/localdatetime/LocalDateTimeAsDateTimeCodec.java import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateEncodeExceptions; import static java.time.Instant.ofEpochMilli; import static java.time.ZoneOffset.UTC; import static java.util.Objects.requireNonNull; import java.time.LocalDateTime; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext; /* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.localdatetime; /** * <p> * Encodes and decodes {@code LocalDateTime} values to and from * {@code BSON DateTime}. * <p> * Note the following implementation details: * <ul> * <li>the zone offset part is considered UTC; * <li>the nanoseconds precision is lost. * </ul> * <p> * This type is <b>immutable</b>. */ public final class LocalDateTimeAsDateTimeCodec implements Codec<LocalDateTime> { @Override public void encode( BsonWriter writer, LocalDateTime value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); translateEncodeExceptions( () -> value, val -> writer.writeDateTime( val.toInstant(UTC) .toEpochMilli() ) ); } @Override public LocalDateTime decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null");
return translateDecodeExceptions(
cbartosiak/bson-codecs-jsr310
src/main/java/io/github/cbartosiak/bson/codecs/jsr310/localtime/LocalTimeAsStringCodec.java
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // }
import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static java.util.Objects.requireNonNull; import java.time.LocalTime; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext;
/* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.localtime; /** * <p> * Encodes and decodes {@code LocalTime} values to and from * {@code BSON String}, such as {@code 10:15:30}. * <p> * The values are stored as {@code ISO-8601} formatted strings * (see {@link LocalTime#toString()}). * <p> * This type is <b>immutable</b>. */ public final class LocalTimeAsStringCodec implements Codec<LocalTime> { @Override public void encode( BsonWriter writer, LocalTime value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); writer.writeString(value.toString()); } @Override public LocalTime decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null");
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/localtime/LocalTimeAsStringCodec.java import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static java.util.Objects.requireNonNull; import java.time.LocalTime; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext; /* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.localtime; /** * <p> * Encodes and decodes {@code LocalTime} values to and from * {@code BSON String}, such as {@code 10:15:30}. * <p> * The values are stored as {@code ISO-8601} formatted strings * (see {@link LocalTime#toString()}). * <p> * This type is <b>immutable</b>. */ public final class LocalTimeAsStringCodec implements Codec<LocalTime> { @Override public void encode( BsonWriter writer, LocalTime value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); writer.writeString(value.toString()); } @Override public LocalTime decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null");
return translateDecodeExceptions(
cbartosiak/bson-codecs-jsr310
src/main/java/io/github/cbartosiak/bson/codecs/jsr310/period/PeriodAsStringCodec.java
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // }
import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static java.util.Objects.requireNonNull; import java.time.Period; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext;
/* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.period; /** * <p> * Encodes and decodes {@code Period} values to and from * {@code BSON String}, such as {@code P18Y1M2D}. * <p> * The values are stored as {@code ISO-8601} formatted strings * (see {@link Period#toString()}). * <p> * This type is <b>immutable</b>. */ public final class PeriodAsStringCodec implements Codec<Period> { @Override public void encode( BsonWriter writer, Period value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); writer.writeString(value.toString()); } @Override public Period decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null");
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/period/PeriodAsStringCodec.java import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static java.util.Objects.requireNonNull; import java.time.Period; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext; /* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.period; /** * <p> * Encodes and decodes {@code Period} values to and from * {@code BSON String}, such as {@code P18Y1M2D}. * <p> * The values are stored as {@code ISO-8601} formatted strings * (see {@link Period#toString()}). * <p> * This type is <b>immutable</b>. */ public final class PeriodAsStringCodec implements Codec<Period> { @Override public void encode( BsonWriter writer, Period value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); writer.writeString(value.toString()); } @Override public Period decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null");
return translateDecodeExceptions(
cbartosiak/bson-codecs-jsr310
src/main/java/io/github/cbartosiak/bson/codecs/jsr310/monthday/MonthDayAsDecimal128Codec.java
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value> void translateEncodeExceptions( // Supplier<Value> valueSupplier, // Consumer<Value> valueConsumer) { // // Value value = valueSupplier.get(); // try { // valueConsumer.accept(value); // } // catch (ArithmeticException | // DateTimeException | // NumberFormatException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // }
import org.bson.codecs.EncoderContext; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateEncodeExceptions; import static java.lang.String.format; import static java.time.MonthDay.of; import static java.util.Objects.requireNonNull; import static org.bson.types.Decimal128.parse; import java.math.BigDecimal; import java.time.MonthDay; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; import org.bson.codecs.DecoderContext;
/* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.monthday; /** * <p> * Encodes and decodes {@code MonthDay} values to and from * {@code BSON Decimal128}, such as {@code 1.02}. * <p> * The values are stored using the following format: {@code %d.%02d} * <ul> * <li>the first part represents a month; * <li>the latter part represents a day of this month. * </ul> * This type is <b>immutable</b>. */ public final class MonthDayAsDecimal128Codec implements Codec<MonthDay> { @Override public void encode( BsonWriter writer, MonthDay value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null");
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value> void translateEncodeExceptions( // Supplier<Value> valueSupplier, // Consumer<Value> valueConsumer) { // // Value value = valueSupplier.get(); // try { // valueConsumer.accept(value); // } // catch (ArithmeticException | // DateTimeException | // NumberFormatException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/monthday/MonthDayAsDecimal128Codec.java import org.bson.codecs.EncoderContext; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateEncodeExceptions; import static java.lang.String.format; import static java.time.MonthDay.of; import static java.util.Objects.requireNonNull; import static org.bson.types.Decimal128.parse; import java.math.BigDecimal; import java.time.MonthDay; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; import org.bson.codecs.DecoderContext; /* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.monthday; /** * <p> * Encodes and decodes {@code MonthDay} values to and from * {@code BSON Decimal128}, such as {@code 1.02}. * <p> * The values are stored using the following format: {@code %d.%02d} * <ul> * <li>the first part represents a month; * <li>the latter part represents a day of this month. * </ul> * This type is <b>immutable</b>. */ public final class MonthDayAsDecimal128Codec implements Codec<MonthDay> { @Override public void encode( BsonWriter writer, MonthDay value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null");
translateEncodeExceptions(
cbartosiak/bson-codecs-jsr310
src/main/java/io/github/cbartosiak/bson/codecs/jsr310/monthday/MonthDayAsDecimal128Codec.java
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value> void translateEncodeExceptions( // Supplier<Value> valueSupplier, // Consumer<Value> valueConsumer) { // // Value value = valueSupplier.get(); // try { // valueConsumer.accept(value); // } // catch (ArithmeticException | // DateTimeException | // NumberFormatException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // }
import org.bson.codecs.EncoderContext; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateEncodeExceptions; import static java.lang.String.format; import static java.time.MonthDay.of; import static java.util.Objects.requireNonNull; import static org.bson.types.Decimal128.parse; import java.math.BigDecimal; import java.time.MonthDay; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; import org.bson.codecs.DecoderContext;
/* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.monthday; /** * <p> * Encodes and decodes {@code MonthDay} values to and from * {@code BSON Decimal128}, such as {@code 1.02}. * <p> * The values are stored using the following format: {@code %d.%02d} * <ul> * <li>the first part represents a month; * <li>the latter part represents a day of this month. * </ul> * This type is <b>immutable</b>. */ public final class MonthDayAsDecimal128Codec implements Codec<MonthDay> { @Override public void encode( BsonWriter writer, MonthDay value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); translateEncodeExceptions( () -> value, val -> writer.writeDecimal128(parse(format( "%d.%02d", val.getMonthValue(), val.getDayOfMonth() ))) ); } @Override public MonthDay decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null");
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value> void translateEncodeExceptions( // Supplier<Value> valueSupplier, // Consumer<Value> valueConsumer) { // // Value value = valueSupplier.get(); // try { // valueConsumer.accept(value); // } // catch (ArithmeticException | // DateTimeException | // NumberFormatException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/monthday/MonthDayAsDecimal128Codec.java import org.bson.codecs.EncoderContext; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateEncodeExceptions; import static java.lang.String.format; import static java.time.MonthDay.of; import static java.util.Objects.requireNonNull; import static org.bson.types.Decimal128.parse; import java.math.BigDecimal; import java.time.MonthDay; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; import org.bson.codecs.DecoderContext; /* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.monthday; /** * <p> * Encodes and decodes {@code MonthDay} values to and from * {@code BSON Decimal128}, such as {@code 1.02}. * <p> * The values are stored using the following format: {@code %d.%02d} * <ul> * <li>the first part represents a month; * <li>the latter part represents a day of this month. * </ul> * This type is <b>immutable</b>. */ public final class MonthDayAsDecimal128Codec implements Codec<MonthDay> { @Override public void encode( BsonWriter writer, MonthDay value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); translateEncodeExceptions( () -> value, val -> writer.writeDecimal128(parse(format( "%d.%02d", val.getMonthValue(), val.getDayOfMonth() ))) ); } @Override public MonthDay decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null");
return translateDecodeExceptions(
cbartosiak/bson-codecs-jsr310
src/main/java/io/github/cbartosiak/bson/codecs/jsr310/localtime/LocalTimeAsInt64Codec.java
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // }
import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static java.util.Objects.requireNonNull; import java.time.LocalTime; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext;
/* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.localtime; /** * <p> * Encodes and decodes {@code LocalTime} values to and from * {@code BSON Int64}, such as {@code 36_930_000_000_000}. * <p> * The values are stored as nanoseconds of a day * (see {@link LocalTime#toNanoOfDay()}). * <p> * This type is <b>immutable</b>. */ public final class LocalTimeAsInt64Codec implements Codec<LocalTime> { @Override public void encode( BsonWriter writer, LocalTime value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); writer.writeInt64(value.toNanoOfDay()); } @Override public LocalTime decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null");
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/localtime/LocalTimeAsInt64Codec.java import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static java.util.Objects.requireNonNull; import java.time.LocalTime; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext; /* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.localtime; /** * <p> * Encodes and decodes {@code LocalTime} values to and from * {@code BSON Int64}, such as {@code 36_930_000_000_000}. * <p> * The values are stored as nanoseconds of a day * (see {@link LocalTime#toNanoOfDay()}). * <p> * This type is <b>immutable</b>. */ public final class LocalTimeAsInt64Codec implements Codec<LocalTime> { @Override public void encode( BsonWriter writer, LocalTime value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); writer.writeInt64(value.toNanoOfDay()); } @Override public LocalTime decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null");
return translateDecodeExceptions(
cbartosiak/bson-codecs-jsr310
src/main/java/io/github/cbartosiak/bson/codecs/jsr310/offsetdatetime/OffsetDateTimeAsStringCodec.java
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // }
import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static java.util.Objects.requireNonNull; import java.time.OffsetDateTime; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext;
/* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.offsetdatetime; /** * <p> * Encodes and decodes {@code OffsetDateTime} values to and from * {@code BSON String}, such as {@code 2018-01-02T10:15:30+01:00}. * <p> * The values are stored as {@code ISO-8601} formatted strings * (see {@link OffsetDateTime#toString()}). * <p> * This type is <b>immutable</b>. */ public final class OffsetDateTimeAsStringCodec implements Codec<OffsetDateTime> { @Override public void encode( BsonWriter writer, OffsetDateTime value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); writer.writeString(value.toString()); } @Override public OffsetDateTime decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null");
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/offsetdatetime/OffsetDateTimeAsStringCodec.java import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static java.util.Objects.requireNonNull; import java.time.OffsetDateTime; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext; /* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.offsetdatetime; /** * <p> * Encodes and decodes {@code OffsetDateTime} values to and from * {@code BSON String}, such as {@code 2018-01-02T10:15:30+01:00}. * <p> * The values are stored as {@code ISO-8601} formatted strings * (see {@link OffsetDateTime#toString()}). * <p> * This type is <b>immutable</b>. */ public final class OffsetDateTimeAsStringCodec implements Codec<OffsetDateTime> { @Override public void encode( BsonWriter writer, OffsetDateTime value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); writer.writeString(value.toString()); } @Override public OffsetDateTime decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null");
return translateDecodeExceptions(
cbartosiak/bson-codecs-jsr310
src/main/java/io/github/cbartosiak/bson/codecs/jsr310/month/MonthAsStringCodec.java
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // }
import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static java.util.Objects.requireNonNull; import java.time.Month; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext;
/* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.month; /** * <p> * Encodes and decodes {@code Month} values to and from * {@code BSON String}, such as {@code JANUARY}. * <p> * The values are stored as enum constant names * (see {@link Month#name()}). * <p> * This type is <b>immutable</b>. */ public final class MonthAsStringCodec implements Codec<Month> { @Override public void encode( BsonWriter writer, Month value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); writer.writeString(value.name()); } @Override public Month decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null");
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/month/MonthAsStringCodec.java import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static java.util.Objects.requireNonNull; import java.time.Month; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext; /* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.month; /** * <p> * Encodes and decodes {@code Month} values to and from * {@code BSON String}, such as {@code JANUARY}. * <p> * The values are stored as enum constant names * (see {@link Month#name()}). * <p> * This type is <b>immutable</b>. */ public final class MonthAsStringCodec implements Codec<Month> { @Override public void encode( BsonWriter writer, Month value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); writer.writeString(value.name()); } @Override public Month decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null");
return translateDecodeExceptions(
cbartosiak/bson-codecs-jsr310
src/main/java/io/github/cbartosiak/bson/codecs/jsr310/duration/DurationAsDocumentCodec.java
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value> Value getFieldValue( // Document document, // Object key, // Class<Value> clazz) { // // try { // Value value = document.get(key, clazz); // if (value == null) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is null", key // )); // } // return value; // } // catch (ClassCastException ex) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is not of the type %s", // key, clazz.getName() // ), ex); // } // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static Document readDocument( // BsonReader reader, // DecoderContext decoderContext, // Map<String, Decoder<?>> fieldDecoders) { // // Document document = new Document(); // reader.readStartDocument(); // while (reader.readBsonType() != END_OF_DOCUMENT) { // String fieldName = reader.readName(); // if (fieldDecoders.containsKey(fieldName)) { // document.put( // fieldName, // fieldDecoders // .get(fieldName) // .decode(reader, decoderContext) // ); // } // else { // throw new BsonInvalidOperationException(format( // "The field %s is not expected here", fieldName // )); // } // } // reader.readEndDocument(); // return document; // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // }
import org.bson.codecs.Decoder; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.getFieldValue; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.readDocument; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static java.time.Duration.ofSeconds; import static java.util.Collections.unmodifiableMap; import static java.util.Objects.requireNonNull; import java.time.Duration; import java.util.HashMap; import java.util.Map; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec;
/* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.duration; /** * <p> * Encodes and decodes {@code Duration} values to and from * {@code BSON Document}, such as {@code { seconds: 10, nanos: 100 }}. * <p> * The values are stored using the following structure: * <ul> * <li>{@code seconds} (a non-null {@code Int64}); * <li>{@code nanos} (a non-null {@code Int32}). * </ul> * <p> * This type is <b>immutable</b>. */ public final class DurationAsDocumentCodec implements Codec<Duration> { private static final Map<String, Decoder<?>> FIELD_DECODERS; static { Map<String, Decoder<?>> fd = new HashMap<>(); fd.put("seconds", (r, dc) -> r.readInt64()); fd.put("nanos", (r, dc) -> r.readInt32()); FIELD_DECODERS = unmodifiableMap(fd); } @Override public void encode( BsonWriter writer, Duration value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); writer.writeStartDocument(); writer.writeInt64("seconds", value.getSeconds()); writer.writeInt32("nanos", value.getNano()); writer.writeEndDocument(); } @Override public Duration decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null");
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value> Value getFieldValue( // Document document, // Object key, // Class<Value> clazz) { // // try { // Value value = document.get(key, clazz); // if (value == null) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is null", key // )); // } // return value; // } // catch (ClassCastException ex) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is not of the type %s", // key, clazz.getName() // ), ex); // } // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static Document readDocument( // BsonReader reader, // DecoderContext decoderContext, // Map<String, Decoder<?>> fieldDecoders) { // // Document document = new Document(); // reader.readStartDocument(); // while (reader.readBsonType() != END_OF_DOCUMENT) { // String fieldName = reader.readName(); // if (fieldDecoders.containsKey(fieldName)) { // document.put( // fieldName, // fieldDecoders // .get(fieldName) // .decode(reader, decoderContext) // ); // } // else { // throw new BsonInvalidOperationException(format( // "The field %s is not expected here", fieldName // )); // } // } // reader.readEndDocument(); // return document; // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/duration/DurationAsDocumentCodec.java import org.bson.codecs.Decoder; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.getFieldValue; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.readDocument; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static java.time.Duration.ofSeconds; import static java.util.Collections.unmodifiableMap; import static java.util.Objects.requireNonNull; import java.time.Duration; import java.util.HashMap; import java.util.Map; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; /* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.duration; /** * <p> * Encodes and decodes {@code Duration} values to and from * {@code BSON Document}, such as {@code { seconds: 10, nanos: 100 }}. * <p> * The values are stored using the following structure: * <ul> * <li>{@code seconds} (a non-null {@code Int64}); * <li>{@code nanos} (a non-null {@code Int32}). * </ul> * <p> * This type is <b>immutable</b>. */ public final class DurationAsDocumentCodec implements Codec<Duration> { private static final Map<String, Decoder<?>> FIELD_DECODERS; static { Map<String, Decoder<?>> fd = new HashMap<>(); fd.put("seconds", (r, dc) -> r.readInt64()); fd.put("nanos", (r, dc) -> r.readInt32()); FIELD_DECODERS = unmodifiableMap(fd); } @Override public void encode( BsonWriter writer, Duration value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); writer.writeStartDocument(); writer.writeInt64("seconds", value.getSeconds()); writer.writeInt32("nanos", value.getNano()); writer.writeEndDocument(); } @Override public Duration decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null");
return translateDecodeExceptions(
cbartosiak/bson-codecs-jsr310
src/main/java/io/github/cbartosiak/bson/codecs/jsr310/duration/DurationAsDocumentCodec.java
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value> Value getFieldValue( // Document document, // Object key, // Class<Value> clazz) { // // try { // Value value = document.get(key, clazz); // if (value == null) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is null", key // )); // } // return value; // } // catch (ClassCastException ex) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is not of the type %s", // key, clazz.getName() // ), ex); // } // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static Document readDocument( // BsonReader reader, // DecoderContext decoderContext, // Map<String, Decoder<?>> fieldDecoders) { // // Document document = new Document(); // reader.readStartDocument(); // while (reader.readBsonType() != END_OF_DOCUMENT) { // String fieldName = reader.readName(); // if (fieldDecoders.containsKey(fieldName)) { // document.put( // fieldName, // fieldDecoders // .get(fieldName) // .decode(reader, decoderContext) // ); // } // else { // throw new BsonInvalidOperationException(format( // "The field %s is not expected here", fieldName // )); // } // } // reader.readEndDocument(); // return document; // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // }
import org.bson.codecs.Decoder; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.getFieldValue; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.readDocument; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static java.time.Duration.ofSeconds; import static java.util.Collections.unmodifiableMap; import static java.util.Objects.requireNonNull; import java.time.Duration; import java.util.HashMap; import java.util.Map; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec;
/* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.duration; /** * <p> * Encodes and decodes {@code Duration} values to and from * {@code BSON Document}, such as {@code { seconds: 10, nanos: 100 }}. * <p> * The values are stored using the following structure: * <ul> * <li>{@code seconds} (a non-null {@code Int64}); * <li>{@code nanos} (a non-null {@code Int32}). * </ul> * <p> * This type is <b>immutable</b>. */ public final class DurationAsDocumentCodec implements Codec<Duration> { private static final Map<String, Decoder<?>> FIELD_DECODERS; static { Map<String, Decoder<?>> fd = new HashMap<>(); fd.put("seconds", (r, dc) -> r.readInt64()); fd.put("nanos", (r, dc) -> r.readInt32()); FIELD_DECODERS = unmodifiableMap(fd); } @Override public void encode( BsonWriter writer, Duration value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); writer.writeStartDocument(); writer.writeInt64("seconds", value.getSeconds()); writer.writeInt32("nanos", value.getNano()); writer.writeEndDocument(); } @Override public Duration decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null"); return translateDecodeExceptions(
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value> Value getFieldValue( // Document document, // Object key, // Class<Value> clazz) { // // try { // Value value = document.get(key, clazz); // if (value == null) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is null", key // )); // } // return value; // } // catch (ClassCastException ex) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is not of the type %s", // key, clazz.getName() // ), ex); // } // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static Document readDocument( // BsonReader reader, // DecoderContext decoderContext, // Map<String, Decoder<?>> fieldDecoders) { // // Document document = new Document(); // reader.readStartDocument(); // while (reader.readBsonType() != END_OF_DOCUMENT) { // String fieldName = reader.readName(); // if (fieldDecoders.containsKey(fieldName)) { // document.put( // fieldName, // fieldDecoders // .get(fieldName) // .decode(reader, decoderContext) // ); // } // else { // throw new BsonInvalidOperationException(format( // "The field %s is not expected here", fieldName // )); // } // } // reader.readEndDocument(); // return document; // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/duration/DurationAsDocumentCodec.java import org.bson.codecs.Decoder; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.getFieldValue; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.readDocument; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static java.time.Duration.ofSeconds; import static java.util.Collections.unmodifiableMap; import static java.util.Objects.requireNonNull; import java.time.Duration; import java.util.HashMap; import java.util.Map; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; /* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.duration; /** * <p> * Encodes and decodes {@code Duration} values to and from * {@code BSON Document}, such as {@code { seconds: 10, nanos: 100 }}. * <p> * The values are stored using the following structure: * <ul> * <li>{@code seconds} (a non-null {@code Int64}); * <li>{@code nanos} (a non-null {@code Int32}). * </ul> * <p> * This type is <b>immutable</b>. */ public final class DurationAsDocumentCodec implements Codec<Duration> { private static final Map<String, Decoder<?>> FIELD_DECODERS; static { Map<String, Decoder<?>> fd = new HashMap<>(); fd.put("seconds", (r, dc) -> r.readInt64()); fd.put("nanos", (r, dc) -> r.readInt32()); FIELD_DECODERS = unmodifiableMap(fd); } @Override public void encode( BsonWriter writer, Duration value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); writer.writeStartDocument(); writer.writeInt64("seconds", value.getSeconds()); writer.writeInt32("nanos", value.getNano()); writer.writeEndDocument(); } @Override public Duration decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null"); return translateDecodeExceptions(
() -> readDocument(reader, decoderContext, FIELD_DECODERS),
cbartosiak/bson-codecs-jsr310
src/main/java/io/github/cbartosiak/bson/codecs/jsr310/duration/DurationAsDocumentCodec.java
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value> Value getFieldValue( // Document document, // Object key, // Class<Value> clazz) { // // try { // Value value = document.get(key, clazz); // if (value == null) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is null", key // )); // } // return value; // } // catch (ClassCastException ex) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is not of the type %s", // key, clazz.getName() // ), ex); // } // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static Document readDocument( // BsonReader reader, // DecoderContext decoderContext, // Map<String, Decoder<?>> fieldDecoders) { // // Document document = new Document(); // reader.readStartDocument(); // while (reader.readBsonType() != END_OF_DOCUMENT) { // String fieldName = reader.readName(); // if (fieldDecoders.containsKey(fieldName)) { // document.put( // fieldName, // fieldDecoders // .get(fieldName) // .decode(reader, decoderContext) // ); // } // else { // throw new BsonInvalidOperationException(format( // "The field %s is not expected here", fieldName // )); // } // } // reader.readEndDocument(); // return document; // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // }
import org.bson.codecs.Decoder; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.getFieldValue; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.readDocument; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static java.time.Duration.ofSeconds; import static java.util.Collections.unmodifiableMap; import static java.util.Objects.requireNonNull; import java.time.Duration; import java.util.HashMap; import java.util.Map; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec;
/* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.duration; /** * <p> * Encodes and decodes {@code Duration} values to and from * {@code BSON Document}, such as {@code { seconds: 10, nanos: 100 }}. * <p> * The values are stored using the following structure: * <ul> * <li>{@code seconds} (a non-null {@code Int64}); * <li>{@code nanos} (a non-null {@code Int32}). * </ul> * <p> * This type is <b>immutable</b>. */ public final class DurationAsDocumentCodec implements Codec<Duration> { private static final Map<String, Decoder<?>> FIELD_DECODERS; static { Map<String, Decoder<?>> fd = new HashMap<>(); fd.put("seconds", (r, dc) -> r.readInt64()); fd.put("nanos", (r, dc) -> r.readInt32()); FIELD_DECODERS = unmodifiableMap(fd); } @Override public void encode( BsonWriter writer, Duration value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); writer.writeStartDocument(); writer.writeInt64("seconds", value.getSeconds()); writer.writeInt32("nanos", value.getNano()); writer.writeEndDocument(); } @Override public Duration decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null"); return translateDecodeExceptions( () -> readDocument(reader, decoderContext, FIELD_DECODERS), val -> ofSeconds(
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value> Value getFieldValue( // Document document, // Object key, // Class<Value> clazz) { // // try { // Value value = document.get(key, clazz); // if (value == null) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is null", key // )); // } // return value; // } // catch (ClassCastException ex) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is not of the type %s", // key, clazz.getName() // ), ex); // } // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static Document readDocument( // BsonReader reader, // DecoderContext decoderContext, // Map<String, Decoder<?>> fieldDecoders) { // // Document document = new Document(); // reader.readStartDocument(); // while (reader.readBsonType() != END_OF_DOCUMENT) { // String fieldName = reader.readName(); // if (fieldDecoders.containsKey(fieldName)) { // document.put( // fieldName, // fieldDecoders // .get(fieldName) // .decode(reader, decoderContext) // ); // } // else { // throw new BsonInvalidOperationException(format( // "The field %s is not expected here", fieldName // )); // } // } // reader.readEndDocument(); // return document; // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/duration/DurationAsDocumentCodec.java import org.bson.codecs.Decoder; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.getFieldValue; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.readDocument; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static java.time.Duration.ofSeconds; import static java.util.Collections.unmodifiableMap; import static java.util.Objects.requireNonNull; import java.time.Duration; import java.util.HashMap; import java.util.Map; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; /* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.duration; /** * <p> * Encodes and decodes {@code Duration} values to and from * {@code BSON Document}, such as {@code { seconds: 10, nanos: 100 }}. * <p> * The values are stored using the following structure: * <ul> * <li>{@code seconds} (a non-null {@code Int64}); * <li>{@code nanos} (a non-null {@code Int32}). * </ul> * <p> * This type is <b>immutable</b>. */ public final class DurationAsDocumentCodec implements Codec<Duration> { private static final Map<String, Decoder<?>> FIELD_DECODERS; static { Map<String, Decoder<?>> fd = new HashMap<>(); fd.put("seconds", (r, dc) -> r.readInt64()); fd.put("nanos", (r, dc) -> r.readInt32()); FIELD_DECODERS = unmodifiableMap(fd); } @Override public void encode( BsonWriter writer, Duration value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); writer.writeStartDocument(); writer.writeInt64("seconds", value.getSeconds()); writer.writeInt32("nanos", value.getNano()); writer.writeEndDocument(); } @Override public Duration decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null"); return translateDecodeExceptions( () -> readDocument(reader, decoderContext, FIELD_DECODERS), val -> ofSeconds(
getFieldValue(val, "seconds", Long.class),
cbartosiak/bson-codecs-jsr310
src/main/java/io/github/cbartosiak/bson/codecs/jsr310/instant/InstantAsDocumentCodec.java
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value> Value getFieldValue( // Document document, // Object key, // Class<Value> clazz) { // // try { // Value value = document.get(key, clazz); // if (value == null) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is null", key // )); // } // return value; // } // catch (ClassCastException ex) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is not of the type %s", // key, clazz.getName() // ), ex); // } // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static Document readDocument( // BsonReader reader, // DecoderContext decoderContext, // Map<String, Decoder<?>> fieldDecoders) { // // Document document = new Document(); // reader.readStartDocument(); // while (reader.readBsonType() != END_OF_DOCUMENT) { // String fieldName = reader.readName(); // if (fieldDecoders.containsKey(fieldName)) { // document.put( // fieldName, // fieldDecoders // .get(fieldName) // .decode(reader, decoderContext) // ); // } // else { // throw new BsonInvalidOperationException(format( // "The field %s is not expected here", fieldName // )); // } // } // reader.readEndDocument(); // return document; // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // }
import org.bson.codecs.Decoder; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.getFieldValue; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.readDocument; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static java.time.Instant.ofEpochSecond; import static java.util.Collections.unmodifiableMap; import static java.util.Objects.requireNonNull; import java.time.Instant; import java.util.HashMap; import java.util.Map; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec;
/* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.instant; /** * <p> * Encodes and decodes {@code Instant} values to and from * {@code BSON Document}, such as {@code { seconds: 1514888130, nanos: 0 }}. * <p> * The values are stored using the following structure: * <ul> * <li>{@code seconds} (a non-null {@code Int64}); * <li>{@code nanos} (a non-null {@code Int32}). * </ul> * <p> * This type is <b>immutable</b>. */ public final class InstantAsDocumentCodec implements Codec<Instant> { private static final Map<String, Decoder<?>> FIELD_DECODERS; static { Map<String, Decoder<?>> fd = new HashMap<>(); fd.put("seconds", (r, dc) -> r.readInt64()); fd.put("nanos", (r, dc) -> r.readInt32()); FIELD_DECODERS = unmodifiableMap(fd); } @Override public void encode( BsonWriter writer, Instant value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); writer.writeStartDocument(); writer.writeInt64("seconds", value.getEpochSecond()); writer.writeInt32("nanos", value.getNano()); writer.writeEndDocument(); } @Override public Instant decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null");
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value> Value getFieldValue( // Document document, // Object key, // Class<Value> clazz) { // // try { // Value value = document.get(key, clazz); // if (value == null) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is null", key // )); // } // return value; // } // catch (ClassCastException ex) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is not of the type %s", // key, clazz.getName() // ), ex); // } // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static Document readDocument( // BsonReader reader, // DecoderContext decoderContext, // Map<String, Decoder<?>> fieldDecoders) { // // Document document = new Document(); // reader.readStartDocument(); // while (reader.readBsonType() != END_OF_DOCUMENT) { // String fieldName = reader.readName(); // if (fieldDecoders.containsKey(fieldName)) { // document.put( // fieldName, // fieldDecoders // .get(fieldName) // .decode(reader, decoderContext) // ); // } // else { // throw new BsonInvalidOperationException(format( // "The field %s is not expected here", fieldName // )); // } // } // reader.readEndDocument(); // return document; // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/instant/InstantAsDocumentCodec.java import org.bson.codecs.Decoder; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.getFieldValue; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.readDocument; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static java.time.Instant.ofEpochSecond; import static java.util.Collections.unmodifiableMap; import static java.util.Objects.requireNonNull; import java.time.Instant; import java.util.HashMap; import java.util.Map; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; /* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.instant; /** * <p> * Encodes and decodes {@code Instant} values to and from * {@code BSON Document}, such as {@code { seconds: 1514888130, nanos: 0 }}. * <p> * The values are stored using the following structure: * <ul> * <li>{@code seconds} (a non-null {@code Int64}); * <li>{@code nanos} (a non-null {@code Int32}). * </ul> * <p> * This type is <b>immutable</b>. */ public final class InstantAsDocumentCodec implements Codec<Instant> { private static final Map<String, Decoder<?>> FIELD_DECODERS; static { Map<String, Decoder<?>> fd = new HashMap<>(); fd.put("seconds", (r, dc) -> r.readInt64()); fd.put("nanos", (r, dc) -> r.readInt32()); FIELD_DECODERS = unmodifiableMap(fd); } @Override public void encode( BsonWriter writer, Instant value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); writer.writeStartDocument(); writer.writeInt64("seconds", value.getEpochSecond()); writer.writeInt32("nanos", value.getNano()); writer.writeEndDocument(); } @Override public Instant decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null");
return translateDecodeExceptions(
cbartosiak/bson-codecs-jsr310
src/main/java/io/github/cbartosiak/bson/codecs/jsr310/instant/InstantAsDocumentCodec.java
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value> Value getFieldValue( // Document document, // Object key, // Class<Value> clazz) { // // try { // Value value = document.get(key, clazz); // if (value == null) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is null", key // )); // } // return value; // } // catch (ClassCastException ex) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is not of the type %s", // key, clazz.getName() // ), ex); // } // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static Document readDocument( // BsonReader reader, // DecoderContext decoderContext, // Map<String, Decoder<?>> fieldDecoders) { // // Document document = new Document(); // reader.readStartDocument(); // while (reader.readBsonType() != END_OF_DOCUMENT) { // String fieldName = reader.readName(); // if (fieldDecoders.containsKey(fieldName)) { // document.put( // fieldName, // fieldDecoders // .get(fieldName) // .decode(reader, decoderContext) // ); // } // else { // throw new BsonInvalidOperationException(format( // "The field %s is not expected here", fieldName // )); // } // } // reader.readEndDocument(); // return document; // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // }
import org.bson.codecs.Decoder; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.getFieldValue; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.readDocument; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static java.time.Instant.ofEpochSecond; import static java.util.Collections.unmodifiableMap; import static java.util.Objects.requireNonNull; import java.time.Instant; import java.util.HashMap; import java.util.Map; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec;
/* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.instant; /** * <p> * Encodes and decodes {@code Instant} values to and from * {@code BSON Document}, such as {@code { seconds: 1514888130, nanos: 0 }}. * <p> * The values are stored using the following structure: * <ul> * <li>{@code seconds} (a non-null {@code Int64}); * <li>{@code nanos} (a non-null {@code Int32}). * </ul> * <p> * This type is <b>immutable</b>. */ public final class InstantAsDocumentCodec implements Codec<Instant> { private static final Map<String, Decoder<?>> FIELD_DECODERS; static { Map<String, Decoder<?>> fd = new HashMap<>(); fd.put("seconds", (r, dc) -> r.readInt64()); fd.put("nanos", (r, dc) -> r.readInt32()); FIELD_DECODERS = unmodifiableMap(fd); } @Override public void encode( BsonWriter writer, Instant value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); writer.writeStartDocument(); writer.writeInt64("seconds", value.getEpochSecond()); writer.writeInt32("nanos", value.getNano()); writer.writeEndDocument(); } @Override public Instant decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null"); return translateDecodeExceptions(
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value> Value getFieldValue( // Document document, // Object key, // Class<Value> clazz) { // // try { // Value value = document.get(key, clazz); // if (value == null) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is null", key // )); // } // return value; // } // catch (ClassCastException ex) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is not of the type %s", // key, clazz.getName() // ), ex); // } // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static Document readDocument( // BsonReader reader, // DecoderContext decoderContext, // Map<String, Decoder<?>> fieldDecoders) { // // Document document = new Document(); // reader.readStartDocument(); // while (reader.readBsonType() != END_OF_DOCUMENT) { // String fieldName = reader.readName(); // if (fieldDecoders.containsKey(fieldName)) { // document.put( // fieldName, // fieldDecoders // .get(fieldName) // .decode(reader, decoderContext) // ); // } // else { // throw new BsonInvalidOperationException(format( // "The field %s is not expected here", fieldName // )); // } // } // reader.readEndDocument(); // return document; // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/instant/InstantAsDocumentCodec.java import org.bson.codecs.Decoder; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.getFieldValue; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.readDocument; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static java.time.Instant.ofEpochSecond; import static java.util.Collections.unmodifiableMap; import static java.util.Objects.requireNonNull; import java.time.Instant; import java.util.HashMap; import java.util.Map; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; /* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.instant; /** * <p> * Encodes and decodes {@code Instant} values to and from * {@code BSON Document}, such as {@code { seconds: 1514888130, nanos: 0 }}. * <p> * The values are stored using the following structure: * <ul> * <li>{@code seconds} (a non-null {@code Int64}); * <li>{@code nanos} (a non-null {@code Int32}). * </ul> * <p> * This type is <b>immutable</b>. */ public final class InstantAsDocumentCodec implements Codec<Instant> { private static final Map<String, Decoder<?>> FIELD_DECODERS; static { Map<String, Decoder<?>> fd = new HashMap<>(); fd.put("seconds", (r, dc) -> r.readInt64()); fd.put("nanos", (r, dc) -> r.readInt32()); FIELD_DECODERS = unmodifiableMap(fd); } @Override public void encode( BsonWriter writer, Instant value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); writer.writeStartDocument(); writer.writeInt64("seconds", value.getEpochSecond()); writer.writeInt32("nanos", value.getNano()); writer.writeEndDocument(); } @Override public Instant decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null"); return translateDecodeExceptions(
() -> readDocument(reader, decoderContext, FIELD_DECODERS),
cbartosiak/bson-codecs-jsr310
src/main/java/io/github/cbartosiak/bson/codecs/jsr310/instant/InstantAsDocumentCodec.java
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value> Value getFieldValue( // Document document, // Object key, // Class<Value> clazz) { // // try { // Value value = document.get(key, clazz); // if (value == null) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is null", key // )); // } // return value; // } // catch (ClassCastException ex) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is not of the type %s", // key, clazz.getName() // ), ex); // } // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static Document readDocument( // BsonReader reader, // DecoderContext decoderContext, // Map<String, Decoder<?>> fieldDecoders) { // // Document document = new Document(); // reader.readStartDocument(); // while (reader.readBsonType() != END_OF_DOCUMENT) { // String fieldName = reader.readName(); // if (fieldDecoders.containsKey(fieldName)) { // document.put( // fieldName, // fieldDecoders // .get(fieldName) // .decode(reader, decoderContext) // ); // } // else { // throw new BsonInvalidOperationException(format( // "The field %s is not expected here", fieldName // )); // } // } // reader.readEndDocument(); // return document; // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // }
import org.bson.codecs.Decoder; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.getFieldValue; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.readDocument; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static java.time.Instant.ofEpochSecond; import static java.util.Collections.unmodifiableMap; import static java.util.Objects.requireNonNull; import java.time.Instant; import java.util.HashMap; import java.util.Map; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec;
/* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.instant; /** * <p> * Encodes and decodes {@code Instant} values to and from * {@code BSON Document}, such as {@code { seconds: 1514888130, nanos: 0 }}. * <p> * The values are stored using the following structure: * <ul> * <li>{@code seconds} (a non-null {@code Int64}); * <li>{@code nanos} (a non-null {@code Int32}). * </ul> * <p> * This type is <b>immutable</b>. */ public final class InstantAsDocumentCodec implements Codec<Instant> { private static final Map<String, Decoder<?>> FIELD_DECODERS; static { Map<String, Decoder<?>> fd = new HashMap<>(); fd.put("seconds", (r, dc) -> r.readInt64()); fd.put("nanos", (r, dc) -> r.readInt32()); FIELD_DECODERS = unmodifiableMap(fd); } @Override public void encode( BsonWriter writer, Instant value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); writer.writeStartDocument(); writer.writeInt64("seconds", value.getEpochSecond()); writer.writeInt32("nanos", value.getNano()); writer.writeEndDocument(); } @Override public Instant decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null"); return translateDecodeExceptions( () -> readDocument(reader, decoderContext, FIELD_DECODERS), val -> ofEpochSecond(
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value> Value getFieldValue( // Document document, // Object key, // Class<Value> clazz) { // // try { // Value value = document.get(key, clazz); // if (value == null) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is null", key // )); // } // return value; // } // catch (ClassCastException ex) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is not of the type %s", // key, clazz.getName() // ), ex); // } // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static Document readDocument( // BsonReader reader, // DecoderContext decoderContext, // Map<String, Decoder<?>> fieldDecoders) { // // Document document = new Document(); // reader.readStartDocument(); // while (reader.readBsonType() != END_OF_DOCUMENT) { // String fieldName = reader.readName(); // if (fieldDecoders.containsKey(fieldName)) { // document.put( // fieldName, // fieldDecoders // .get(fieldName) // .decode(reader, decoderContext) // ); // } // else { // throw new BsonInvalidOperationException(format( // "The field %s is not expected here", fieldName // )); // } // } // reader.readEndDocument(); // return document; // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/instant/InstantAsDocumentCodec.java import org.bson.codecs.Decoder; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.getFieldValue; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.readDocument; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static java.time.Instant.ofEpochSecond; import static java.util.Collections.unmodifiableMap; import static java.util.Objects.requireNonNull; import java.time.Instant; import java.util.HashMap; import java.util.Map; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; /* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.instant; /** * <p> * Encodes and decodes {@code Instant} values to and from * {@code BSON Document}, such as {@code { seconds: 1514888130, nanos: 0 }}. * <p> * The values are stored using the following structure: * <ul> * <li>{@code seconds} (a non-null {@code Int64}); * <li>{@code nanos} (a non-null {@code Int32}). * </ul> * <p> * This type is <b>immutable</b>. */ public final class InstantAsDocumentCodec implements Codec<Instant> { private static final Map<String, Decoder<?>> FIELD_DECODERS; static { Map<String, Decoder<?>> fd = new HashMap<>(); fd.put("seconds", (r, dc) -> r.readInt64()); fd.put("nanos", (r, dc) -> r.readInt32()); FIELD_DECODERS = unmodifiableMap(fd); } @Override public void encode( BsonWriter writer, Instant value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); writer.writeStartDocument(); writer.writeInt64("seconds", value.getEpochSecond()); writer.writeInt32("nanos", value.getNano()); writer.writeEndDocument(); } @Override public Instant decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null"); return translateDecodeExceptions( () -> readDocument(reader, decoderContext, FIELD_DECODERS), val -> ofEpochSecond(
getFieldValue(val, "seconds", Long.class),
cbartosiak/bson-codecs-jsr310
src/main/java/io/github/cbartosiak/bson/codecs/jsr310/localdate/LocalDateAsDateTimeCodec.java
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value> void translateEncodeExceptions( // Supplier<Value> valueSupplier, // Consumer<Value> valueConsumer) { // // Value value = valueSupplier.get(); // try { // valueConsumer.accept(value); // } // catch (ArithmeticException | // DateTimeException | // NumberFormatException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // }
import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateEncodeExceptions; import static java.time.Instant.ofEpochMilli; import static java.time.ZoneOffset.UTC; import static java.util.Objects.requireNonNull; import java.time.LocalDate; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext;
/* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.localdate; /** * <p> * Encodes and decodes {@code LocalDate} values to and from * {@code BSON DateTime}. * <p> * Note the following implementation details: * <ul> * <li>the time part is considered midnight; * <li>the zone offset part is considered UTC. * </ul> * <p> * This type is <b>immutable</b>. */ public final class LocalDateAsDateTimeCodec implements Codec<LocalDate> { @Override public void encode( BsonWriter writer, LocalDate value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null");
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value> void translateEncodeExceptions( // Supplier<Value> valueSupplier, // Consumer<Value> valueConsumer) { // // Value value = valueSupplier.get(); // try { // valueConsumer.accept(value); // } // catch (ArithmeticException | // DateTimeException | // NumberFormatException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/localdate/LocalDateAsDateTimeCodec.java import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateEncodeExceptions; import static java.time.Instant.ofEpochMilli; import static java.time.ZoneOffset.UTC; import static java.util.Objects.requireNonNull; import java.time.LocalDate; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext; /* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.localdate; /** * <p> * Encodes and decodes {@code LocalDate} values to and from * {@code BSON DateTime}. * <p> * Note the following implementation details: * <ul> * <li>the time part is considered midnight; * <li>the zone offset part is considered UTC. * </ul> * <p> * This type is <b>immutable</b>. */ public final class LocalDateAsDateTimeCodec implements Codec<LocalDate> { @Override public void encode( BsonWriter writer, LocalDate value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null");
translateEncodeExceptions(
cbartosiak/bson-codecs-jsr310
src/main/java/io/github/cbartosiak/bson/codecs/jsr310/localdate/LocalDateAsDateTimeCodec.java
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value> void translateEncodeExceptions( // Supplier<Value> valueSupplier, // Consumer<Value> valueConsumer) { // // Value value = valueSupplier.get(); // try { // valueConsumer.accept(value); // } // catch (ArithmeticException | // DateTimeException | // NumberFormatException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // }
import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateEncodeExceptions; import static java.time.Instant.ofEpochMilli; import static java.time.ZoneOffset.UTC; import static java.util.Objects.requireNonNull; import java.time.LocalDate; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext;
/* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.localdate; /** * <p> * Encodes and decodes {@code LocalDate} values to and from * {@code BSON DateTime}. * <p> * Note the following implementation details: * <ul> * <li>the time part is considered midnight; * <li>the zone offset part is considered UTC. * </ul> * <p> * This type is <b>immutable</b>. */ public final class LocalDateAsDateTimeCodec implements Codec<LocalDate> { @Override public void encode( BsonWriter writer, LocalDate value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); translateEncodeExceptions( () -> value, val -> writer.writeDateTime( val.atStartOfDay() .toInstant(UTC) .toEpochMilli() ) ); } @Override public LocalDate decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null");
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value> void translateEncodeExceptions( // Supplier<Value> valueSupplier, // Consumer<Value> valueConsumer) { // // Value value = valueSupplier.get(); // try { // valueConsumer.accept(value); // } // catch (ArithmeticException | // DateTimeException | // NumberFormatException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/localdate/LocalDateAsDateTimeCodec.java import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateEncodeExceptions; import static java.time.Instant.ofEpochMilli; import static java.time.ZoneOffset.UTC; import static java.util.Objects.requireNonNull; import java.time.LocalDate; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext; /* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.localdate; /** * <p> * Encodes and decodes {@code LocalDate} values to and from * {@code BSON DateTime}. * <p> * Note the following implementation details: * <ul> * <li>the time part is considered midnight; * <li>the zone offset part is considered UTC. * </ul> * <p> * This type is <b>immutable</b>. */ public final class LocalDateAsDateTimeCodec implements Codec<LocalDate> { @Override public void encode( BsonWriter writer, LocalDate value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); translateEncodeExceptions( () -> value, val -> writer.writeDateTime( val.atStartOfDay() .toInstant(UTC) .toEpochMilli() ) ); } @Override public LocalDate decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null");
return translateDecodeExceptions(
cbartosiak/bson-codecs-jsr310
src/main/java/io/github/cbartosiak/bson/codecs/jsr310/zoneoffset/ZoneOffsetAsInt32Codec.java
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // }
import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static java.util.Objects.requireNonNull; import java.time.ZoneOffset; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext;
/* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.zoneoffset; /** * <p> * Encodes and decodes {@code ZoneOffset} values to and from * {@code BSON Int32}, such as {@code 3_600}. * <p> * The values are stored as total zone offset amounts in seconds * (see {@link ZoneOffset#getTotalSeconds()}). * <p> * This type is <b>immutable</b>. */ public final class ZoneOffsetAsInt32Codec implements Codec<ZoneOffset> { @Override public void encode( BsonWriter writer, ZoneOffset value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); writer.writeInt32(value.getTotalSeconds()); } @Override public ZoneOffset decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null");
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/zoneoffset/ZoneOffsetAsInt32Codec.java import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static java.util.Objects.requireNonNull; import java.time.ZoneOffset; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext; /* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.zoneoffset; /** * <p> * Encodes and decodes {@code ZoneOffset} values to and from * {@code BSON Int32}, such as {@code 3_600}. * <p> * The values are stored as total zone offset amounts in seconds * (see {@link ZoneOffset#getTotalSeconds()}). * <p> * This type is <b>immutable</b>. */ public final class ZoneOffsetAsInt32Codec implements Codec<ZoneOffset> { @Override public void encode( BsonWriter writer, ZoneOffset value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); writer.writeInt32(value.getTotalSeconds()); } @Override public ZoneOffset decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null");
return translateDecodeExceptions(
cbartosiak/bson-codecs-jsr310
src/main/java/io/github/cbartosiak/bson/codecs/jsr310/zoneddatetime/ZonedDateTimeAsStringCodec.java
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // }
import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static java.util.Objects.requireNonNull; import java.time.ZonedDateTime; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext;
/* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.zoneddatetime; /** * <p> * Encodes and decodes {@code ZonedDateTime} values to and from * {@code BSON String}, such as {@code 2018-01-02T10:15:30+01:00[CET]}. * <p> * The values are stored as <i>quasi</i> {@code ISO-8601} formatted strings * (see {@link ZonedDateTime#toString()}). * <p> * This type is <b>immutable</b>. */ public final class ZonedDateTimeAsStringCodec implements Codec<ZonedDateTime> { @Override public void encode( BsonWriter writer, ZonedDateTime value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); writer.writeString(value.toString()); } @Override public ZonedDateTime decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null");
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/zoneddatetime/ZonedDateTimeAsStringCodec.java import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static java.util.Objects.requireNonNull; import java.time.ZonedDateTime; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext; /* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.zoneddatetime; /** * <p> * Encodes and decodes {@code ZonedDateTime} values to and from * {@code BSON String}, such as {@code 2018-01-02T10:15:30+01:00[CET]}. * <p> * The values are stored as <i>quasi</i> {@code ISO-8601} formatted strings * (see {@link ZonedDateTime#toString()}). * <p> * This type is <b>immutable</b>. */ public final class ZonedDateTimeAsStringCodec implements Codec<ZonedDateTime> { @Override public void encode( BsonWriter writer, ZonedDateTime value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); writer.writeString(value.toString()); } @Override public ZonedDateTime decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null");
return translateDecodeExceptions(
cbartosiak/bson-codecs-jsr310
src/main/java/io/github/cbartosiak/bson/codecs/jsr310/monthday/MonthDayAsStringCodec.java
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // }
import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static java.util.Objects.requireNonNull; import java.time.MonthDay; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext;
/* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.monthday; /** * <p> * Encodes and decodes {@code MonthDay} values to and from * {@code BSON String}, such as {@code --01-02}. * <p> * The values are stored as <i>quasi</i> {@code ISO-8601} formatted strings * (see {@link MonthDay}). * <p> * This type is <b>immutable</b>. */ public final class MonthDayAsStringCodec implements Codec<MonthDay> { @Override public void encode( BsonWriter writer, MonthDay value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); writer.writeString(value.toString()); } @Override public MonthDay decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null");
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/monthday/MonthDayAsStringCodec.java import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static java.util.Objects.requireNonNull; import java.time.MonthDay; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext; /* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.monthday; /** * <p> * Encodes and decodes {@code MonthDay} values to and from * {@code BSON String}, such as {@code --01-02}. * <p> * The values are stored as <i>quasi</i> {@code ISO-8601} formatted strings * (see {@link MonthDay}). * <p> * This type is <b>immutable</b>. */ public final class MonthDayAsStringCodec implements Codec<MonthDay> { @Override public void encode( BsonWriter writer, MonthDay value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); writer.writeString(value.toString()); } @Override public MonthDay decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null");
return translateDecodeExceptions(
cbartosiak/bson-codecs-jsr310
src/main/java/io/github/cbartosiak/bson/codecs/jsr310/month/MonthAsInt32Codec.java
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // }
import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static java.util.Objects.requireNonNull; import java.time.Month; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext;
/* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.month; /** * <p> * Encodes and decodes {@code Month} values to and from * {@code BSON Int32}, such as {@code 1}. * <p> * The values are stored as {@code ISO-8601} integers * (see {@link Month#getValue()}). * <p> * This type is <b>immutable</b>. */ public final class MonthAsInt32Codec implements Codec<Month> { @Override public void encode( BsonWriter writer, Month value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); writer.writeInt32(value.getValue()); } @Override public Month decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null");
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/month/MonthAsInt32Codec.java import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static java.util.Objects.requireNonNull; import java.time.Month; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext; /* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.month; /** * <p> * Encodes and decodes {@code Month} values to and from * {@code BSON Int32}, such as {@code 1}. * <p> * The values are stored as {@code ISO-8601} integers * (see {@link Month#getValue()}). * <p> * This type is <b>immutable</b>. */ public final class MonthAsInt32Codec implements Codec<Month> { @Override public void encode( BsonWriter writer, Month value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); writer.writeInt32(value.getValue()); } @Override public Month decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null");
return translateDecodeExceptions(
cbartosiak/bson-codecs-jsr310
src/main/java/io/github/cbartosiak/bson/codecs/jsr310/duration/DurationAsDecimal128Codec.java
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value> void translateEncodeExceptions( // Supplier<Value> valueSupplier, // Consumer<Value> valueConsumer) { // // Value value = valueSupplier.get(); // try { // valueConsumer.accept(value); // } // catch (ArithmeticException | // DateTimeException | // NumberFormatException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // }
import org.bson.codecs.EncoderContext; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateEncodeExceptions; import static java.lang.String.format; import static java.time.Duration.ofSeconds; import static java.util.Objects.requireNonNull; import static org.bson.types.Decimal128.parse; import java.math.BigDecimal; import java.time.Duration; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; import org.bson.codecs.DecoderContext;
/* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.duration; /** * <p> * Encodes and decodes {@code Duration} values to and from * {@code BSON Decimal128}, such as {@code 10.100_000_000}. * <p> * The values are stored using the following format: {@code %d.%09d} * <ul> * <li>the first part represents seconds; * <li>the latter part represents nanoseconds. * </ul> * <p> * This type is <b>immutable</b>. */ public final class DurationAsDecimal128Codec implements Codec<Duration> { @Override public void encode( BsonWriter writer, Duration value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null");
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value> void translateEncodeExceptions( // Supplier<Value> valueSupplier, // Consumer<Value> valueConsumer) { // // Value value = valueSupplier.get(); // try { // valueConsumer.accept(value); // } // catch (ArithmeticException | // DateTimeException | // NumberFormatException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/duration/DurationAsDecimal128Codec.java import org.bson.codecs.EncoderContext; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateEncodeExceptions; import static java.lang.String.format; import static java.time.Duration.ofSeconds; import static java.util.Objects.requireNonNull; import static org.bson.types.Decimal128.parse; import java.math.BigDecimal; import java.time.Duration; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; import org.bson.codecs.DecoderContext; /* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.duration; /** * <p> * Encodes and decodes {@code Duration} values to and from * {@code BSON Decimal128}, such as {@code 10.100_000_000}. * <p> * The values are stored using the following format: {@code %d.%09d} * <ul> * <li>the first part represents seconds; * <li>the latter part represents nanoseconds. * </ul> * <p> * This type is <b>immutable</b>. */ public final class DurationAsDecimal128Codec implements Codec<Duration> { @Override public void encode( BsonWriter writer, Duration value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null");
translateEncodeExceptions(
cbartosiak/bson-codecs-jsr310
src/main/java/io/github/cbartosiak/bson/codecs/jsr310/duration/DurationAsDecimal128Codec.java
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value> void translateEncodeExceptions( // Supplier<Value> valueSupplier, // Consumer<Value> valueConsumer) { // // Value value = valueSupplier.get(); // try { // valueConsumer.accept(value); // } // catch (ArithmeticException | // DateTimeException | // NumberFormatException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // }
import org.bson.codecs.EncoderContext; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateEncodeExceptions; import static java.lang.String.format; import static java.time.Duration.ofSeconds; import static java.util.Objects.requireNonNull; import static org.bson.types.Decimal128.parse; import java.math.BigDecimal; import java.time.Duration; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; import org.bson.codecs.DecoderContext;
/* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.duration; /** * <p> * Encodes and decodes {@code Duration} values to and from * {@code BSON Decimal128}, such as {@code 10.100_000_000}. * <p> * The values are stored using the following format: {@code %d.%09d} * <ul> * <li>the first part represents seconds; * <li>the latter part represents nanoseconds. * </ul> * <p> * This type is <b>immutable</b>. */ public final class DurationAsDecimal128Codec implements Codec<Duration> { @Override public void encode( BsonWriter writer, Duration value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); translateEncodeExceptions( () -> value, val -> writer.writeDecimal128(parse(format( "%d.%09d", val.getSeconds(), val.getNano() ))) ); } @Override public Duration decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null");
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value> void translateEncodeExceptions( // Supplier<Value> valueSupplier, // Consumer<Value> valueConsumer) { // // Value value = valueSupplier.get(); // try { // valueConsumer.accept(value); // } // catch (ArithmeticException | // DateTimeException | // NumberFormatException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/duration/DurationAsDecimal128Codec.java import org.bson.codecs.EncoderContext; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateEncodeExceptions; import static java.lang.String.format; import static java.time.Duration.ofSeconds; import static java.util.Objects.requireNonNull; import static org.bson.types.Decimal128.parse; import java.math.BigDecimal; import java.time.Duration; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; import org.bson.codecs.DecoderContext; /* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.duration; /** * <p> * Encodes and decodes {@code Duration} values to and from * {@code BSON Decimal128}, such as {@code 10.100_000_000}. * <p> * The values are stored using the following format: {@code %d.%09d} * <ul> * <li>the first part represents seconds; * <li>the latter part represents nanoseconds. * </ul> * <p> * This type is <b>immutable</b>. */ public final class DurationAsDecimal128Codec implements Codec<Duration> { @Override public void encode( BsonWriter writer, Duration value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); translateEncodeExceptions( () -> value, val -> writer.writeDecimal128(parse(format( "%d.%09d", val.getSeconds(), val.getNano() ))) ); } @Override public Duration decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null");
return translateDecodeExceptions(
cbartosiak/bson-codecs-jsr310
src/main/java/io/github/cbartosiak/bson/codecs/jsr310/yearmonth/YearMonthAsDocumentCodec.java
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value> Value getFieldValue( // Document document, // Object key, // Class<Value> clazz) { // // try { // Value value = document.get(key, clazz); // if (value == null) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is null", key // )); // } // return value; // } // catch (ClassCastException ex) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is not of the type %s", // key, clazz.getName() // ), ex); // } // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static Document readDocument( // BsonReader reader, // DecoderContext decoderContext, // Map<String, Decoder<?>> fieldDecoders) { // // Document document = new Document(); // reader.readStartDocument(); // while (reader.readBsonType() != END_OF_DOCUMENT) { // String fieldName = reader.readName(); // if (fieldDecoders.containsKey(fieldName)) { // document.put( // fieldName, // fieldDecoders // .get(fieldName) // .decode(reader, decoderContext) // ); // } // else { // throw new BsonInvalidOperationException(format( // "The field %s is not expected here", fieldName // )); // } // } // reader.readEndDocument(); // return document; // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // }
import org.bson.codecs.Decoder; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.getFieldValue; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.readDocument; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static java.time.YearMonth.of; import static java.util.Collections.unmodifiableMap; import static java.util.Objects.requireNonNull; import java.time.YearMonth; import java.util.HashMap; import java.util.Map; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec;
/* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.yearmonth; /** * <p> * Encodes and decodes {@code YearMonth} values to and from * {@code BSON Document}, such as {@code { year: 2018, month: 1 }}. * <p> * The values are stored using the following structure: * <ul> * <li>{@code year} (a non-null {@code Int32}); * <li>{@code month} (a non-null {@code Int32}). * </ul> * <p> * This type is <b>immutable</b>. */ public final class YearMonthAsDocumentCodec implements Codec<YearMonth> { private static final Map<String, Decoder<?>> FIELD_DECODERS; static { Map<String, Decoder<?>> fd = new HashMap<>(); fd.put("year", (r, dc) -> r.readInt32()); fd.put("month", (r, dc) -> r.readInt32()); FIELD_DECODERS = unmodifiableMap(fd); } @Override public void encode( BsonWriter writer, YearMonth value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); writer.writeStartDocument(); writer.writeInt32("year", value.getYear()); writer.writeInt32("month", value.getMonthValue()); writer.writeEndDocument(); } @Override public YearMonth decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null");
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value> Value getFieldValue( // Document document, // Object key, // Class<Value> clazz) { // // try { // Value value = document.get(key, clazz); // if (value == null) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is null", key // )); // } // return value; // } // catch (ClassCastException ex) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is not of the type %s", // key, clazz.getName() // ), ex); // } // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static Document readDocument( // BsonReader reader, // DecoderContext decoderContext, // Map<String, Decoder<?>> fieldDecoders) { // // Document document = new Document(); // reader.readStartDocument(); // while (reader.readBsonType() != END_OF_DOCUMENT) { // String fieldName = reader.readName(); // if (fieldDecoders.containsKey(fieldName)) { // document.put( // fieldName, // fieldDecoders // .get(fieldName) // .decode(reader, decoderContext) // ); // } // else { // throw new BsonInvalidOperationException(format( // "The field %s is not expected here", fieldName // )); // } // } // reader.readEndDocument(); // return document; // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/yearmonth/YearMonthAsDocumentCodec.java import org.bson.codecs.Decoder; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.getFieldValue; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.readDocument; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static java.time.YearMonth.of; import static java.util.Collections.unmodifiableMap; import static java.util.Objects.requireNonNull; import java.time.YearMonth; import java.util.HashMap; import java.util.Map; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; /* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.yearmonth; /** * <p> * Encodes and decodes {@code YearMonth} values to and from * {@code BSON Document}, such as {@code { year: 2018, month: 1 }}. * <p> * The values are stored using the following structure: * <ul> * <li>{@code year} (a non-null {@code Int32}); * <li>{@code month} (a non-null {@code Int32}). * </ul> * <p> * This type is <b>immutable</b>. */ public final class YearMonthAsDocumentCodec implements Codec<YearMonth> { private static final Map<String, Decoder<?>> FIELD_DECODERS; static { Map<String, Decoder<?>> fd = new HashMap<>(); fd.put("year", (r, dc) -> r.readInt32()); fd.put("month", (r, dc) -> r.readInt32()); FIELD_DECODERS = unmodifiableMap(fd); } @Override public void encode( BsonWriter writer, YearMonth value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); writer.writeStartDocument(); writer.writeInt32("year", value.getYear()); writer.writeInt32("month", value.getMonthValue()); writer.writeEndDocument(); } @Override public YearMonth decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null");
return translateDecodeExceptions(
cbartosiak/bson-codecs-jsr310
src/main/java/io/github/cbartosiak/bson/codecs/jsr310/yearmonth/YearMonthAsDocumentCodec.java
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value> Value getFieldValue( // Document document, // Object key, // Class<Value> clazz) { // // try { // Value value = document.get(key, clazz); // if (value == null) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is null", key // )); // } // return value; // } // catch (ClassCastException ex) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is not of the type %s", // key, clazz.getName() // ), ex); // } // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static Document readDocument( // BsonReader reader, // DecoderContext decoderContext, // Map<String, Decoder<?>> fieldDecoders) { // // Document document = new Document(); // reader.readStartDocument(); // while (reader.readBsonType() != END_OF_DOCUMENT) { // String fieldName = reader.readName(); // if (fieldDecoders.containsKey(fieldName)) { // document.put( // fieldName, // fieldDecoders // .get(fieldName) // .decode(reader, decoderContext) // ); // } // else { // throw new BsonInvalidOperationException(format( // "The field %s is not expected here", fieldName // )); // } // } // reader.readEndDocument(); // return document; // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // }
import org.bson.codecs.Decoder; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.getFieldValue; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.readDocument; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static java.time.YearMonth.of; import static java.util.Collections.unmodifiableMap; import static java.util.Objects.requireNonNull; import java.time.YearMonth; import java.util.HashMap; import java.util.Map; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec;
/* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.yearmonth; /** * <p> * Encodes and decodes {@code YearMonth} values to and from * {@code BSON Document}, such as {@code { year: 2018, month: 1 }}. * <p> * The values are stored using the following structure: * <ul> * <li>{@code year} (a non-null {@code Int32}); * <li>{@code month} (a non-null {@code Int32}). * </ul> * <p> * This type is <b>immutable</b>. */ public final class YearMonthAsDocumentCodec implements Codec<YearMonth> { private static final Map<String, Decoder<?>> FIELD_DECODERS; static { Map<String, Decoder<?>> fd = new HashMap<>(); fd.put("year", (r, dc) -> r.readInt32()); fd.put("month", (r, dc) -> r.readInt32()); FIELD_DECODERS = unmodifiableMap(fd); } @Override public void encode( BsonWriter writer, YearMonth value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); writer.writeStartDocument(); writer.writeInt32("year", value.getYear()); writer.writeInt32("month", value.getMonthValue()); writer.writeEndDocument(); } @Override public YearMonth decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null"); return translateDecodeExceptions(
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value> Value getFieldValue( // Document document, // Object key, // Class<Value> clazz) { // // try { // Value value = document.get(key, clazz); // if (value == null) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is null", key // )); // } // return value; // } // catch (ClassCastException ex) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is not of the type %s", // key, clazz.getName() // ), ex); // } // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static Document readDocument( // BsonReader reader, // DecoderContext decoderContext, // Map<String, Decoder<?>> fieldDecoders) { // // Document document = new Document(); // reader.readStartDocument(); // while (reader.readBsonType() != END_OF_DOCUMENT) { // String fieldName = reader.readName(); // if (fieldDecoders.containsKey(fieldName)) { // document.put( // fieldName, // fieldDecoders // .get(fieldName) // .decode(reader, decoderContext) // ); // } // else { // throw new BsonInvalidOperationException(format( // "The field %s is not expected here", fieldName // )); // } // } // reader.readEndDocument(); // return document; // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/yearmonth/YearMonthAsDocumentCodec.java import org.bson.codecs.Decoder; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.getFieldValue; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.readDocument; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static java.time.YearMonth.of; import static java.util.Collections.unmodifiableMap; import static java.util.Objects.requireNonNull; import java.time.YearMonth; import java.util.HashMap; import java.util.Map; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; /* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.yearmonth; /** * <p> * Encodes and decodes {@code YearMonth} values to and from * {@code BSON Document}, such as {@code { year: 2018, month: 1 }}. * <p> * The values are stored using the following structure: * <ul> * <li>{@code year} (a non-null {@code Int32}); * <li>{@code month} (a non-null {@code Int32}). * </ul> * <p> * This type is <b>immutable</b>. */ public final class YearMonthAsDocumentCodec implements Codec<YearMonth> { private static final Map<String, Decoder<?>> FIELD_DECODERS; static { Map<String, Decoder<?>> fd = new HashMap<>(); fd.put("year", (r, dc) -> r.readInt32()); fd.put("month", (r, dc) -> r.readInt32()); FIELD_DECODERS = unmodifiableMap(fd); } @Override public void encode( BsonWriter writer, YearMonth value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); writer.writeStartDocument(); writer.writeInt32("year", value.getYear()); writer.writeInt32("month", value.getMonthValue()); writer.writeEndDocument(); } @Override public YearMonth decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null"); return translateDecodeExceptions(
() -> readDocument(reader, decoderContext, FIELD_DECODERS),
cbartosiak/bson-codecs-jsr310
src/main/java/io/github/cbartosiak/bson/codecs/jsr310/yearmonth/YearMonthAsDocumentCodec.java
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value> Value getFieldValue( // Document document, // Object key, // Class<Value> clazz) { // // try { // Value value = document.get(key, clazz); // if (value == null) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is null", key // )); // } // return value; // } // catch (ClassCastException ex) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is not of the type %s", // key, clazz.getName() // ), ex); // } // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static Document readDocument( // BsonReader reader, // DecoderContext decoderContext, // Map<String, Decoder<?>> fieldDecoders) { // // Document document = new Document(); // reader.readStartDocument(); // while (reader.readBsonType() != END_OF_DOCUMENT) { // String fieldName = reader.readName(); // if (fieldDecoders.containsKey(fieldName)) { // document.put( // fieldName, // fieldDecoders // .get(fieldName) // .decode(reader, decoderContext) // ); // } // else { // throw new BsonInvalidOperationException(format( // "The field %s is not expected here", fieldName // )); // } // } // reader.readEndDocument(); // return document; // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // }
import org.bson.codecs.Decoder; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.getFieldValue; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.readDocument; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static java.time.YearMonth.of; import static java.util.Collections.unmodifiableMap; import static java.util.Objects.requireNonNull; import java.time.YearMonth; import java.util.HashMap; import java.util.Map; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec;
/* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.yearmonth; /** * <p> * Encodes and decodes {@code YearMonth} values to and from * {@code BSON Document}, such as {@code { year: 2018, month: 1 }}. * <p> * The values are stored using the following structure: * <ul> * <li>{@code year} (a non-null {@code Int32}); * <li>{@code month} (a non-null {@code Int32}). * </ul> * <p> * This type is <b>immutable</b>. */ public final class YearMonthAsDocumentCodec implements Codec<YearMonth> { private static final Map<String, Decoder<?>> FIELD_DECODERS; static { Map<String, Decoder<?>> fd = new HashMap<>(); fd.put("year", (r, dc) -> r.readInt32()); fd.put("month", (r, dc) -> r.readInt32()); FIELD_DECODERS = unmodifiableMap(fd); } @Override public void encode( BsonWriter writer, YearMonth value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); writer.writeStartDocument(); writer.writeInt32("year", value.getYear()); writer.writeInt32("month", value.getMonthValue()); writer.writeEndDocument(); } @Override public YearMonth decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null"); return translateDecodeExceptions( () -> readDocument(reader, decoderContext, FIELD_DECODERS), val -> of(
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value> Value getFieldValue( // Document document, // Object key, // Class<Value> clazz) { // // try { // Value value = document.get(key, clazz); // if (value == null) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is null", key // )); // } // return value; // } // catch (ClassCastException ex) { // throw new BsonInvalidOperationException(format( // "The value of the field %s is not of the type %s", // key, clazz.getName() // ), ex); // } // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static Document readDocument( // BsonReader reader, // DecoderContext decoderContext, // Map<String, Decoder<?>> fieldDecoders) { // // Document document = new Document(); // reader.readStartDocument(); // while (reader.readBsonType() != END_OF_DOCUMENT) { // String fieldName = reader.readName(); // if (fieldDecoders.containsKey(fieldName)) { // document.put( // fieldName, // fieldDecoders // .get(fieldName) // .decode(reader, decoderContext) // ); // } // else { // throw new BsonInvalidOperationException(format( // "The field %s is not expected here", fieldName // )); // } // } // reader.readEndDocument(); // return document; // } // // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/yearmonth/YearMonthAsDocumentCodec.java import org.bson.codecs.Decoder; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.getFieldValue; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.readDocument; import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static java.time.YearMonth.of; import static java.util.Collections.unmodifiableMap; import static java.util.Objects.requireNonNull; import java.time.YearMonth; import java.util.HashMap; import java.util.Map; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; /* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.yearmonth; /** * <p> * Encodes and decodes {@code YearMonth} values to and from * {@code BSON Document}, such as {@code { year: 2018, month: 1 }}. * <p> * The values are stored using the following structure: * <ul> * <li>{@code year} (a non-null {@code Int32}); * <li>{@code month} (a non-null {@code Int32}). * </ul> * <p> * This type is <b>immutable</b>. */ public final class YearMonthAsDocumentCodec implements Codec<YearMonth> { private static final Map<String, Decoder<?>> FIELD_DECODERS; static { Map<String, Decoder<?>> fd = new HashMap<>(); fd.put("year", (r, dc) -> r.readInt32()); fd.put("month", (r, dc) -> r.readInt32()); FIELD_DECODERS = unmodifiableMap(fd); } @Override public void encode( BsonWriter writer, YearMonth value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); writer.writeStartDocument(); writer.writeInt32("year", value.getYear()); writer.writeInt32("month", value.getMonthValue()); writer.writeEndDocument(); } @Override public YearMonth decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null"); return translateDecodeExceptions( () -> readDocument(reader, decoderContext, FIELD_DECODERS), val -> of(
getFieldValue(val, "year", Integer.class),
cbartosiak/bson-codecs-jsr310
src/main/java/io/github/cbartosiak/bson/codecs/jsr310/zoneid/ZoneIdAsStringCodec.java
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // }
import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static java.util.Objects.requireNonNull; import java.time.ZoneId; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext;
/* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.zoneid; /** * <p> * Encodes and decodes {@code ZoneId} values to and from * {@code BSON String}, such as * {@code CET} (non-offset based IDs) or * {@code +01:00} (offset based IDs). * <p> * The values are stored as IDs * (see {@link ZoneId#getId()}). * <p> * This type is <b>immutable</b>. */ public final class ZoneIdAsStringCodec implements Codec<ZoneId> { @Override public void encode( BsonWriter writer, ZoneId value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); writer.writeString(value.getId()); } @Override public ZoneId decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null");
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/zoneid/ZoneIdAsStringCodec.java import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static java.util.Objects.requireNonNull; import java.time.ZoneId; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext; /* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.zoneid; /** * <p> * Encodes and decodes {@code ZoneId} values to and from * {@code BSON String}, such as * {@code CET} (non-offset based IDs) or * {@code +01:00} (offset based IDs). * <p> * The values are stored as IDs * (see {@link ZoneId#getId()}). * <p> * This type is <b>immutable</b>. */ public final class ZoneIdAsStringCodec implements Codec<ZoneId> { @Override public void encode( BsonWriter writer, ZoneId value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); writer.writeString(value.getId()); } @Override public ZoneId decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null");
return translateDecodeExceptions(
cbartosiak/bson-codecs-jsr310
src/main/java/io/github/cbartosiak/bson/codecs/jsr310/yearmonth/YearMonthAsStringCodec.java
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // }
import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static java.util.Objects.requireNonNull; import java.time.YearMonth; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext;
/* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.yearmonth; /** * <p> * Encodes and decodes {@code YearMonth} values to and from * {@code BSON String}, such as {@code 2018-01}. * <p> * The values are stored as <i>quasi</i> {@code ISO-8601} formatted strings * (see {@link YearMonth}). Note that the years greater than * {@code 9999} are prefixed with the {@code +} sign. * <p> * This type is <b>immutable</b>. */ public final class YearMonthAsStringCodec implements Codec<YearMonth> { @Override public void encode( BsonWriter writer, YearMonth value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); writer.writeString((value.getYear() > 9999 ? "+" : "") + value); } @Override public YearMonth decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null");
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/yearmonth/YearMonthAsStringCodec.java import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static java.util.Objects.requireNonNull; import java.time.YearMonth; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext; /* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.yearmonth; /** * <p> * Encodes and decodes {@code YearMonth} values to and from * {@code BSON String}, such as {@code 2018-01}. * <p> * The values are stored as <i>quasi</i> {@code ISO-8601} formatted strings * (see {@link YearMonth}). Note that the years greater than * {@code 9999} are prefixed with the {@code +} sign. * <p> * This type is <b>immutable</b>. */ public final class YearMonthAsStringCodec implements Codec<YearMonth> { @Override public void encode( BsonWriter writer, YearMonth value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); writer.writeString((value.getYear() > 9999 ? "+" : "") + value); } @Override public YearMonth decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null");
return translateDecodeExceptions(
cbartosiak/bson-codecs-jsr310
src/main/java/io/github/cbartosiak/bson/codecs/jsr310/localdatetime/LocalDateTimeAsStringCodec.java
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // }
import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static java.util.Objects.requireNonNull; import java.time.LocalDateTime; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext;
/* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.localdatetime; /** * <p> * Encodes and decodes {@code LocalDateTime} values to and from * {@code BSON String}, such as {@code 2018-01-02T10:15:30}. * <p> * The values are stored as {@code ISO-8601} formatted strings * (see {@link LocalDateTime#toString()}). * <p> * This type is <b>immutable</b>. */ public final class LocalDateTimeAsStringCodec implements Codec<LocalDateTime> { @Override public void encode( BsonWriter writer, LocalDateTime value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); writer.writeString(value.toString()); } @Override public LocalDateTime decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null");
// Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/internal/CodecsUtil.java // public static <Value, Result> Result translateDecodeExceptions( // Supplier<Value> valueSupplier, // Function<Value, Result> valueConverter) { // // Value value = valueSupplier.get(); // try { // return valueConverter.apply(value); // } // catch (ArithmeticException | // DateTimeException | // IllegalArgumentException ex) { // // throw new BsonInvalidOperationException(format( // "The value %s is not supported", value // ), ex); // } // } // Path: src/main/java/io/github/cbartosiak/bson/codecs/jsr310/localdatetime/LocalDateTimeAsStringCodec.java import static io.github.cbartosiak.bson.codecs.jsr310.internal.CodecsUtil.translateDecodeExceptions; import static java.util.Objects.requireNonNull; import java.time.LocalDateTime; import org.bson.BsonReader; import org.bson.BsonWriter; import org.bson.codecs.Codec; import org.bson.codecs.DecoderContext; import org.bson.codecs.EncoderContext; /* * Copyright 2018 Cezary Bartosiak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.cbartosiak.bson.codecs.jsr310.localdatetime; /** * <p> * Encodes and decodes {@code LocalDateTime} values to and from * {@code BSON String}, such as {@code 2018-01-02T10:15:30}. * <p> * The values are stored as {@code ISO-8601} formatted strings * (see {@link LocalDateTime#toString()}). * <p> * This type is <b>immutable</b>. */ public final class LocalDateTimeAsStringCodec implements Codec<LocalDateTime> { @Override public void encode( BsonWriter writer, LocalDateTime value, EncoderContext encoderContext) { requireNonNull(writer, "writer is null"); requireNonNull(value, "value is null"); writer.writeString(value.toString()); } @Override public LocalDateTime decode( BsonReader reader, DecoderContext decoderContext) { requireNonNull(reader, "reader is null");
return translateDecodeExceptions(