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
onepf/OPFPush
opfpush/src/main/java/org/onepf/opfpush/utils/CheckUtils.java
// Path: opfpush/src/main/java/org/onepf/opfpush/listener/CheckManifestHandler.java // public interface CheckManifestHandler { // // /** // * Called when some check manifest error occurred. // * // * @param reportMessage The information about error. // */ // void onCheckManifestError(@NonNull final String reportMessage); // }
import java.util.List; import java.util.Locale; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.text.TextUtils; import org.onepf.opfpush.listener.CheckManifestHandler; import org.onepf.opfutils.OPFChecks;
/* * Copyright 2012-2015 One Platform Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onepf.opfpush.utils; /** * @author Roman Savin * @since 22.04.2015 */ public final class CheckUtils { private static final String LINE_SEPARATOR = System.getProperty("line.separator"); private CheckUtils() { throw new UnsupportedOperationException(); } /** * Checks is a service has been described in the AndroidManifest.xml file. * * @param context The instance of {@link android.content.Context}. * @param service The checked service. */ @SuppressWarnings("PMD.PreserveStackTrace") public static void checkService(@NonNull final Context context, @NonNull final ComponentName service,
// Path: opfpush/src/main/java/org/onepf/opfpush/listener/CheckManifestHandler.java // public interface CheckManifestHandler { // // /** // * Called when some check manifest error occurred. // * // * @param reportMessage The information about error. // */ // void onCheckManifestError(@NonNull final String reportMessage); // } // Path: opfpush/src/main/java/org/onepf/opfpush/utils/CheckUtils.java import java.util.List; import java.util.Locale; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.text.TextUtils; import org.onepf.opfpush.listener.CheckManifestHandler; import org.onepf.opfutils.OPFChecks; /* * Copyright 2012-2015 One Platform Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onepf.opfpush.utils; /** * @author Roman Savin * @since 22.04.2015 */ public final class CheckUtils { private static final String LINE_SEPARATOR = System.getProperty("line.separator"); private CheckUtils() { throw new UnsupportedOperationException(); } /** * Checks is a service has been described in the AndroidManifest.xml file. * * @param context The instance of {@link android.content.Context}. * @param service The checked service. */ @SuppressWarnings("PMD.PreserveStackTrace") public static void checkService(@NonNull final Context context, @NonNull final ComponentName service,
@Nullable final CheckManifestHandler checkManifestHandler) {
onepf/OPFPush
opfpush/src/main/java/org/onepf/opfpush/backoff/UnregisterBackoffAdapter.java
// Path: opfpush/src/main/java/org/onepf/opfpush/model/Operation.java // public enum Operation { // REGISTER, // UNREGISTER // }
import android.support.annotation.NonNull; import org.onepf.opfutils.OPFLog; import org.onepf.opfpush.model.Operation; import java.util.HashMap; import java.util.Map; import static org.onepf.opfpush.model.Operation.UNREGISTER;
/* * Copyright 2012-2015 One Platform Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onepf.opfpush.backoff; /** * @author Roman Savin * @since 03.02.2015 */ final class UnregisterBackoffAdapter<T extends Backoff> implements BackoffManager { @NonNull private final Class<T> backoffClass; @NonNull private final Map<String, Backoff> backoffMap = new HashMap<>(); public UnregisterBackoffAdapter(@NonNull final Class<T> backoffClass) { this.backoffClass = backoffClass; } @Override public boolean hasTries(@NonNull final String providerName,
// Path: opfpush/src/main/java/org/onepf/opfpush/model/Operation.java // public enum Operation { // REGISTER, // UNREGISTER // } // Path: opfpush/src/main/java/org/onepf/opfpush/backoff/UnregisterBackoffAdapter.java import android.support.annotation.NonNull; import org.onepf.opfutils.OPFLog; import org.onepf.opfpush.model.Operation; import java.util.HashMap; import java.util.Map; import static org.onepf.opfpush.model.Operation.UNREGISTER; /* * Copyright 2012-2015 One Platform Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onepf.opfpush.backoff; /** * @author Roman Savin * @since 03.02.2015 */ final class UnregisterBackoffAdapter<T extends Backoff> implements BackoffManager { @NonNull private final Class<T> backoffClass; @NonNull private final Map<String, Backoff> backoffMap = new HashMap<>(); public UnregisterBackoffAdapter(@NonNull final Class<T> backoffClass) { this.backoffClass = backoffClass; } @Override public boolean hasTries(@NonNull final String providerName,
@NonNull final Operation operation) {
onepf/OPFPush
samples/pushchat/src/main/java/org/onepf/pushchat/ui/adapter/MessagesCursorAdapter.java
// Path: samples/pushchat/src/main/java/org/onepf/pushchat/db/ContentDescriptor.java // public static final String MESSAGE = "message"; // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/db/ContentDescriptor.java // public static final String RECEIVED_TIME = "received_time"; // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/db/ContentDescriptor.java // public static final String SENDER_NAME = "sender_name"; // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/db/ContentDescriptor.java // public static final String SENDER_UUID = "sender_uuid";
import static org.onepf.pushchat.db.ContentDescriptor.MessagesContract.MessageEntry.RECEIVED_TIME; import static org.onepf.pushchat.db.ContentDescriptor.MessagesContract.MessageEntry.SENDER_NAME; import static org.onepf.pushchat.db.ContentDescriptor.MessagesContract.MessageEntry.SENDER_UUID; import android.content.Context; import android.database.Cursor; import android.support.annotation.NonNull; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CursorAdapter; import android.widget.TextView; import org.onepf.pushchat.R; import java.util.Date; import static org.onepf.pushchat.db.ContentDescriptor.MessagesContract.MessageEntry.MESSAGE;
/* * Copyright 2012-2015 One Platform Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onepf.pushchat.ui.adapter; /** * @author Roman Savin * @since 06.05.2015 */ public class MessagesCursorAdapter extends CursorAdapter { private static final int TYPE_COUNT = 2; private static final int ODD_ITEM = 1; public MessagesCursorAdapter(@NonNull final Context context) { super(context, null, true); } @Override public int getItemViewType(final int position) { return position % 2; } @Override public int getViewTypeCount() { return TYPE_COUNT; } @Override public View newView(final Context context, final Cursor cursor, final ViewGroup parent) { final View view = LayoutInflater.from(context).inflate(R.layout.item_message, parent, false); if (getItemViewType(cursor.getPosition()) == ODD_ITEM) { view.setBackgroundResource(R.drawable.odd_message_item_selector); } return view; } @Override public void bindView(final View view, final Context context, final Cursor cursor) {
// Path: samples/pushchat/src/main/java/org/onepf/pushchat/db/ContentDescriptor.java // public static final String MESSAGE = "message"; // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/db/ContentDescriptor.java // public static final String RECEIVED_TIME = "received_time"; // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/db/ContentDescriptor.java // public static final String SENDER_NAME = "sender_name"; // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/db/ContentDescriptor.java // public static final String SENDER_UUID = "sender_uuid"; // Path: samples/pushchat/src/main/java/org/onepf/pushchat/ui/adapter/MessagesCursorAdapter.java import static org.onepf.pushchat.db.ContentDescriptor.MessagesContract.MessageEntry.RECEIVED_TIME; import static org.onepf.pushchat.db.ContentDescriptor.MessagesContract.MessageEntry.SENDER_NAME; import static org.onepf.pushchat.db.ContentDescriptor.MessagesContract.MessageEntry.SENDER_UUID; import android.content.Context; import android.database.Cursor; import android.support.annotation.NonNull; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CursorAdapter; import android.widget.TextView; import org.onepf.pushchat.R; import java.util.Date; import static org.onepf.pushchat.db.ContentDescriptor.MessagesContract.MessageEntry.MESSAGE; /* * Copyright 2012-2015 One Platform Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onepf.pushchat.ui.adapter; /** * @author Roman Savin * @since 06.05.2015 */ public class MessagesCursorAdapter extends CursorAdapter { private static final int TYPE_COUNT = 2; private static final int ODD_ITEM = 1; public MessagesCursorAdapter(@NonNull final Context context) { super(context, null, true); } @Override public int getItemViewType(final int position) { return position % 2; } @Override public int getViewTypeCount() { return TYPE_COUNT; } @Override public View newView(final Context context, final Cursor cursor, final ViewGroup parent) { final View view = LayoutInflater.from(context).inflate(R.layout.item_message, parent, false); if (getItemViewType(cursor.getPosition()) == ODD_ITEM) { view.setBackgroundResource(R.drawable.odd_message_item_selector); } return view; } @Override public void bindView(final View view, final Context context, final Cursor cursor) {
final String senderUuid = cursor.getString(cursor.getColumnIndexOrThrow(SENDER_UUID));
onepf/OPFPush
samples/pushchat/src/main/java/org/onepf/pushchat/ui/adapter/MessagesCursorAdapter.java
// Path: samples/pushchat/src/main/java/org/onepf/pushchat/db/ContentDescriptor.java // public static final String MESSAGE = "message"; // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/db/ContentDescriptor.java // public static final String RECEIVED_TIME = "received_time"; // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/db/ContentDescriptor.java // public static final String SENDER_NAME = "sender_name"; // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/db/ContentDescriptor.java // public static final String SENDER_UUID = "sender_uuid";
import static org.onepf.pushchat.db.ContentDescriptor.MessagesContract.MessageEntry.RECEIVED_TIME; import static org.onepf.pushchat.db.ContentDescriptor.MessagesContract.MessageEntry.SENDER_NAME; import static org.onepf.pushchat.db.ContentDescriptor.MessagesContract.MessageEntry.SENDER_UUID; import android.content.Context; import android.database.Cursor; import android.support.annotation.NonNull; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CursorAdapter; import android.widget.TextView; import org.onepf.pushchat.R; import java.util.Date; import static org.onepf.pushchat.db.ContentDescriptor.MessagesContract.MessageEntry.MESSAGE;
/* * Copyright 2012-2015 One Platform Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onepf.pushchat.ui.adapter; /** * @author Roman Savin * @since 06.05.2015 */ public class MessagesCursorAdapter extends CursorAdapter { private static final int TYPE_COUNT = 2; private static final int ODD_ITEM = 1; public MessagesCursorAdapter(@NonNull final Context context) { super(context, null, true); } @Override public int getItemViewType(final int position) { return position % 2; } @Override public int getViewTypeCount() { return TYPE_COUNT; } @Override public View newView(final Context context, final Cursor cursor, final ViewGroup parent) { final View view = LayoutInflater.from(context).inflate(R.layout.item_message, parent, false); if (getItemViewType(cursor.getPosition()) == ODD_ITEM) { view.setBackgroundResource(R.drawable.odd_message_item_selector); } return view; } @Override public void bindView(final View view, final Context context, final Cursor cursor) { final String senderUuid = cursor.getString(cursor.getColumnIndexOrThrow(SENDER_UUID));
// Path: samples/pushchat/src/main/java/org/onepf/pushchat/db/ContentDescriptor.java // public static final String MESSAGE = "message"; // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/db/ContentDescriptor.java // public static final String RECEIVED_TIME = "received_time"; // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/db/ContentDescriptor.java // public static final String SENDER_NAME = "sender_name"; // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/db/ContentDescriptor.java // public static final String SENDER_UUID = "sender_uuid"; // Path: samples/pushchat/src/main/java/org/onepf/pushchat/ui/adapter/MessagesCursorAdapter.java import static org.onepf.pushchat.db.ContentDescriptor.MessagesContract.MessageEntry.RECEIVED_TIME; import static org.onepf.pushchat.db.ContentDescriptor.MessagesContract.MessageEntry.SENDER_NAME; import static org.onepf.pushchat.db.ContentDescriptor.MessagesContract.MessageEntry.SENDER_UUID; import android.content.Context; import android.database.Cursor; import android.support.annotation.NonNull; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CursorAdapter; import android.widget.TextView; import org.onepf.pushchat.R; import java.util.Date; import static org.onepf.pushchat.db.ContentDescriptor.MessagesContract.MessageEntry.MESSAGE; /* * Copyright 2012-2015 One Platform Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onepf.pushchat.ui.adapter; /** * @author Roman Savin * @since 06.05.2015 */ public class MessagesCursorAdapter extends CursorAdapter { private static final int TYPE_COUNT = 2; private static final int ODD_ITEM = 1; public MessagesCursorAdapter(@NonNull final Context context) { super(context, null, true); } @Override public int getItemViewType(final int position) { return position % 2; } @Override public int getViewTypeCount() { return TYPE_COUNT; } @Override public View newView(final Context context, final Cursor cursor, final ViewGroup parent) { final View view = LayoutInflater.from(context).inflate(R.layout.item_message, parent, false); if (getItemViewType(cursor.getPosition()) == ODD_ITEM) { view.setBackgroundResource(R.drawable.odd_message_item_selector); } return view; } @Override public void bindView(final View view, final Context context, final Cursor cursor) { final String senderUuid = cursor.getString(cursor.getColumnIndexOrThrow(SENDER_UUID));
final String senderName = cursor.getString(cursor.getColumnIndexOrThrow(SENDER_NAME));
onepf/OPFPush
samples/pushchat/src/main/java/org/onepf/pushchat/ui/adapter/MessagesCursorAdapter.java
// Path: samples/pushchat/src/main/java/org/onepf/pushchat/db/ContentDescriptor.java // public static final String MESSAGE = "message"; // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/db/ContentDescriptor.java // public static final String RECEIVED_TIME = "received_time"; // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/db/ContentDescriptor.java // public static final String SENDER_NAME = "sender_name"; // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/db/ContentDescriptor.java // public static final String SENDER_UUID = "sender_uuid";
import static org.onepf.pushchat.db.ContentDescriptor.MessagesContract.MessageEntry.RECEIVED_TIME; import static org.onepf.pushchat.db.ContentDescriptor.MessagesContract.MessageEntry.SENDER_NAME; import static org.onepf.pushchat.db.ContentDescriptor.MessagesContract.MessageEntry.SENDER_UUID; import android.content.Context; import android.database.Cursor; import android.support.annotation.NonNull; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CursorAdapter; import android.widget.TextView; import org.onepf.pushchat.R; import java.util.Date; import static org.onepf.pushchat.db.ContentDescriptor.MessagesContract.MessageEntry.MESSAGE;
/* * Copyright 2012-2015 One Platform Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onepf.pushchat.ui.adapter; /** * @author Roman Savin * @since 06.05.2015 */ public class MessagesCursorAdapter extends CursorAdapter { private static final int TYPE_COUNT = 2; private static final int ODD_ITEM = 1; public MessagesCursorAdapter(@NonNull final Context context) { super(context, null, true); } @Override public int getItemViewType(final int position) { return position % 2; } @Override public int getViewTypeCount() { return TYPE_COUNT; } @Override public View newView(final Context context, final Cursor cursor, final ViewGroup parent) { final View view = LayoutInflater.from(context).inflate(R.layout.item_message, parent, false); if (getItemViewType(cursor.getPosition()) == ODD_ITEM) { view.setBackgroundResource(R.drawable.odd_message_item_selector); } return view; } @Override public void bindView(final View view, final Context context, final Cursor cursor) { final String senderUuid = cursor.getString(cursor.getColumnIndexOrThrow(SENDER_UUID)); final String senderName = cursor.getString(cursor.getColumnIndexOrThrow(SENDER_NAME));
// Path: samples/pushchat/src/main/java/org/onepf/pushchat/db/ContentDescriptor.java // public static final String MESSAGE = "message"; // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/db/ContentDescriptor.java // public static final String RECEIVED_TIME = "received_time"; // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/db/ContentDescriptor.java // public static final String SENDER_NAME = "sender_name"; // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/db/ContentDescriptor.java // public static final String SENDER_UUID = "sender_uuid"; // Path: samples/pushchat/src/main/java/org/onepf/pushchat/ui/adapter/MessagesCursorAdapter.java import static org.onepf.pushchat.db.ContentDescriptor.MessagesContract.MessageEntry.RECEIVED_TIME; import static org.onepf.pushchat.db.ContentDescriptor.MessagesContract.MessageEntry.SENDER_NAME; import static org.onepf.pushchat.db.ContentDescriptor.MessagesContract.MessageEntry.SENDER_UUID; import android.content.Context; import android.database.Cursor; import android.support.annotation.NonNull; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CursorAdapter; import android.widget.TextView; import org.onepf.pushchat.R; import java.util.Date; import static org.onepf.pushchat.db.ContentDescriptor.MessagesContract.MessageEntry.MESSAGE; /* * Copyright 2012-2015 One Platform Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onepf.pushchat.ui.adapter; /** * @author Roman Savin * @since 06.05.2015 */ public class MessagesCursorAdapter extends CursorAdapter { private static final int TYPE_COUNT = 2; private static final int ODD_ITEM = 1; public MessagesCursorAdapter(@NonNull final Context context) { super(context, null, true); } @Override public int getItemViewType(final int position) { return position % 2; } @Override public int getViewTypeCount() { return TYPE_COUNT; } @Override public View newView(final Context context, final Cursor cursor, final ViewGroup parent) { final View view = LayoutInflater.from(context).inflate(R.layout.item_message, parent, false); if (getItemViewType(cursor.getPosition()) == ODD_ITEM) { view.setBackgroundResource(R.drawable.odd_message_item_selector); } return view; } @Override public void bindView(final View view, final Context context, final Cursor cursor) { final String senderUuid = cursor.getString(cursor.getColumnIndexOrThrow(SENDER_UUID)); final String senderName = cursor.getString(cursor.getColumnIndexOrThrow(SENDER_NAME));
final String message = cursor.getString(cursor.getColumnIndexOrThrow(MESSAGE));
onepf/OPFPush
samples/pushchat/src/main/java/org/onepf/pushchat/ui/adapter/MessagesCursorAdapter.java
// Path: samples/pushchat/src/main/java/org/onepf/pushchat/db/ContentDescriptor.java // public static final String MESSAGE = "message"; // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/db/ContentDescriptor.java // public static final String RECEIVED_TIME = "received_time"; // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/db/ContentDescriptor.java // public static final String SENDER_NAME = "sender_name"; // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/db/ContentDescriptor.java // public static final String SENDER_UUID = "sender_uuid";
import static org.onepf.pushchat.db.ContentDescriptor.MessagesContract.MessageEntry.RECEIVED_TIME; import static org.onepf.pushchat.db.ContentDescriptor.MessagesContract.MessageEntry.SENDER_NAME; import static org.onepf.pushchat.db.ContentDescriptor.MessagesContract.MessageEntry.SENDER_UUID; import android.content.Context; import android.database.Cursor; import android.support.annotation.NonNull; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CursorAdapter; import android.widget.TextView; import org.onepf.pushchat.R; import java.util.Date; import static org.onepf.pushchat.db.ContentDescriptor.MessagesContract.MessageEntry.MESSAGE;
/* * Copyright 2012-2015 One Platform Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onepf.pushchat.ui.adapter; /** * @author Roman Savin * @since 06.05.2015 */ public class MessagesCursorAdapter extends CursorAdapter { private static final int TYPE_COUNT = 2; private static final int ODD_ITEM = 1; public MessagesCursorAdapter(@NonNull final Context context) { super(context, null, true); } @Override public int getItemViewType(final int position) { return position % 2; } @Override public int getViewTypeCount() { return TYPE_COUNT; } @Override public View newView(final Context context, final Cursor cursor, final ViewGroup parent) { final View view = LayoutInflater.from(context).inflate(R.layout.item_message, parent, false); if (getItemViewType(cursor.getPosition()) == ODD_ITEM) { view.setBackgroundResource(R.drawable.odd_message_item_selector); } return view; } @Override public void bindView(final View view, final Context context, final Cursor cursor) { final String senderUuid = cursor.getString(cursor.getColumnIndexOrThrow(SENDER_UUID)); final String senderName = cursor.getString(cursor.getColumnIndexOrThrow(SENDER_NAME)); final String message = cursor.getString(cursor.getColumnIndexOrThrow(MESSAGE));
// Path: samples/pushchat/src/main/java/org/onepf/pushchat/db/ContentDescriptor.java // public static final String MESSAGE = "message"; // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/db/ContentDescriptor.java // public static final String RECEIVED_TIME = "received_time"; // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/db/ContentDescriptor.java // public static final String SENDER_NAME = "sender_name"; // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/db/ContentDescriptor.java // public static final String SENDER_UUID = "sender_uuid"; // Path: samples/pushchat/src/main/java/org/onepf/pushchat/ui/adapter/MessagesCursorAdapter.java import static org.onepf.pushchat.db.ContentDescriptor.MessagesContract.MessageEntry.RECEIVED_TIME; import static org.onepf.pushchat.db.ContentDescriptor.MessagesContract.MessageEntry.SENDER_NAME; import static org.onepf.pushchat.db.ContentDescriptor.MessagesContract.MessageEntry.SENDER_UUID; import android.content.Context; import android.database.Cursor; import android.support.annotation.NonNull; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CursorAdapter; import android.widget.TextView; import org.onepf.pushchat.R; import java.util.Date; import static org.onepf.pushchat.db.ContentDescriptor.MessagesContract.MessageEntry.MESSAGE; /* * Copyright 2012-2015 One Platform Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onepf.pushchat.ui.adapter; /** * @author Roman Savin * @since 06.05.2015 */ public class MessagesCursorAdapter extends CursorAdapter { private static final int TYPE_COUNT = 2; private static final int ODD_ITEM = 1; public MessagesCursorAdapter(@NonNull final Context context) { super(context, null, true); } @Override public int getItemViewType(final int position) { return position % 2; } @Override public int getViewTypeCount() { return TYPE_COUNT; } @Override public View newView(final Context context, final Cursor cursor, final ViewGroup parent) { final View view = LayoutInflater.from(context).inflate(R.layout.item_message, parent, false); if (getItemViewType(cursor.getPosition()) == ODD_ITEM) { view.setBackgroundResource(R.drawable.odd_message_item_selector); } return view; } @Override public void bindView(final View view, final Context context, final Cursor cursor) { final String senderUuid = cursor.getString(cursor.getColumnIndexOrThrow(SENDER_UUID)); final String senderName = cursor.getString(cursor.getColumnIndexOrThrow(SENDER_NAME)); final String message = cursor.getString(cursor.getColumnIndexOrThrow(MESSAGE));
final long time = cursor.getLong(cursor.getColumnIndexOrThrow(RECEIVED_TIME));
onepf/OPFPush
opfpush-providers/gcm/src/main/java/org/onepf/opfpush/gcm/SendMessageService.java
// Path: opfpush/src/main/java/org/onepf/opfpush/model/Message.java // public class Message implements Parcelable { // // public static final Creator<Message> CREATOR = new Creator<Message>() { // // @Override // public Message createFromParcel(Parcel source) { // return new Message(source); // } // // @Override // public Message[] newArray(int size) { // return new Message[size]; // } // }; // // private final String id; // private final Bundle data; // private final long timeToLeave; // // /** // * Create new message. // * // * @param id Message's ID. // * @param data Messages' data to send. // */ // public Message(@NonNull final String id, @NonNull final Bundle data) { // this(id, data, 0); // } // // /** // * Create new message. // * // * @param id Message's ID. // * @param data Messages' data to send. // * @param timeToLeave How long message is valid. Set 0 to default value. // * @throws java.lang.IllegalArgumentException If {@code timeToLeave} is negative. // */ // public Message(@NonNull final String id, @NonNull final Bundle data, final long timeToLeave) { // if (timeToLeave < 0) { // throw new IllegalArgumentException(String.format("timeToLeave='%d'." // + " Time to leave must be non negative value.", timeToLeave)); // } // this.id = id; // this.data = data; // this.timeToLeave = timeToLeave; // } // // private Message(final Parcel parcel) { // id = parcel.readString(); // timeToLeave = parcel.readLong(); // data = parcel.readBundle(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(id); // dest.writeLong(timeToLeave); // dest.writeBundle(data); // } // // @NonNull // public String getId() { // return id; // } // // @NonNull // public Bundle getData() { // return data; // } // // public long getTimeToLeave() { // return timeToLeave; // } // // @NonNull // @Override // public String toString() { // return "Message{" // + "messageId='" + id + '\'' // + ", data='" + OPFUtils.toString(data) // + '\'' // + ", TTL='" + timeToLeave + '\'' // + '}'; // } // }
import android.app.IntentService; import android.content.Intent; import com.google.android.gms.gcm.GoogleCloudMessaging; import org.onepf.opfpush.model.Message; import org.onepf.opfutils.OPFLog; import org.onepf.opfutils.OPFUtils; import java.io.IOException;
/* * Copyright 2012-2015 One Platform Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onepf.opfpush.gcm; /** * @author Kirill Rozov * @author Roman Savin * @since 10/13/14. */ public class SendMessageService extends IntentService { public static final String ACTION_SEND_MESSAGE = "org.onepf.opfpush.gcm.SEND_MSG"; public static final String EXTRA_MESSAGE = "msg"; public static final String EXTRA_MESSAGES_TO = "to"; public SendMessageService() { super("SendMessageService"); } @Override protected void onHandleIntent(final Intent intent) { OPFLog.logMethod(OPFUtils.toString(intent)); if (ACTION_SEND_MESSAGE.equals(intent.getAction())) {
// Path: opfpush/src/main/java/org/onepf/opfpush/model/Message.java // public class Message implements Parcelable { // // public static final Creator<Message> CREATOR = new Creator<Message>() { // // @Override // public Message createFromParcel(Parcel source) { // return new Message(source); // } // // @Override // public Message[] newArray(int size) { // return new Message[size]; // } // }; // // private final String id; // private final Bundle data; // private final long timeToLeave; // // /** // * Create new message. // * // * @param id Message's ID. // * @param data Messages' data to send. // */ // public Message(@NonNull final String id, @NonNull final Bundle data) { // this(id, data, 0); // } // // /** // * Create new message. // * // * @param id Message's ID. // * @param data Messages' data to send. // * @param timeToLeave How long message is valid. Set 0 to default value. // * @throws java.lang.IllegalArgumentException If {@code timeToLeave} is negative. // */ // public Message(@NonNull final String id, @NonNull final Bundle data, final long timeToLeave) { // if (timeToLeave < 0) { // throw new IllegalArgumentException(String.format("timeToLeave='%d'." // + " Time to leave must be non negative value.", timeToLeave)); // } // this.id = id; // this.data = data; // this.timeToLeave = timeToLeave; // } // // private Message(final Parcel parcel) { // id = parcel.readString(); // timeToLeave = parcel.readLong(); // data = parcel.readBundle(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(id); // dest.writeLong(timeToLeave); // dest.writeBundle(data); // } // // @NonNull // public String getId() { // return id; // } // // @NonNull // public Bundle getData() { // return data; // } // // public long getTimeToLeave() { // return timeToLeave; // } // // @NonNull // @Override // public String toString() { // return "Message{" // + "messageId='" + id + '\'' // + ", data='" + OPFUtils.toString(data) // + '\'' // + ", TTL='" + timeToLeave + '\'' // + '}'; // } // } // Path: opfpush-providers/gcm/src/main/java/org/onepf/opfpush/gcm/SendMessageService.java import android.app.IntentService; import android.content.Intent; import com.google.android.gms.gcm.GoogleCloudMessaging; import org.onepf.opfpush.model.Message; import org.onepf.opfutils.OPFLog; import org.onepf.opfutils.OPFUtils; import java.io.IOException; /* * Copyright 2012-2015 One Platform Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onepf.opfpush.gcm; /** * @author Kirill Rozov * @author Roman Savin * @since 10/13/14. */ public class SendMessageService extends IntentService { public static final String ACTION_SEND_MESSAGE = "org.onepf.opfpush.gcm.SEND_MSG"; public static final String EXTRA_MESSAGE = "msg"; public static final String EXTRA_MESSAGES_TO = "to"; public SendMessageService() { super("SendMessageService"); } @Override protected void onHandleIntent(final Intent intent) { OPFLog.logMethod(OPFUtils.toString(intent)); if (ACTION_SEND_MESSAGE.equals(intent.getAction())) {
final Message message = intent.getParcelableExtra(EXTRA_MESSAGE);
onepf/OPFPush
opfpush-providers/gcm/src/main/java/org/onepf/opfpush/gcm/GCMService.java
// Path: opfpush/src/main/java/org/onepf/opfpush/OPFConstants.java // public final class OPFConstants { // // /** // * Indicates unknown count of deleted messages. // */ // public static final int MESSAGES_COUNT_UNKNOWN = Integer.MIN_VALUE; // // public static final String EXTRA_PROVIDER_NAME = "org.onepf.opfpush.intent.EXTRA_PROVIDER_NAME"; // public static final String EXTRA_REGISTRATION_ID = "org.onepf.opfpush.intent.EXTRA_REGISTRATION_ID"; // public static final String EXTRA_MESSAGE_TYPE = "org.onepf.opfpush.intent.EXTRA_MESSAGE_TYPE"; // public static final String EXTRA_MESSAGE_COUNT = "org.onepf.opfpush.intent.EXTRA_MESSAGE_COUNT"; // public static final String EXTRA_REGISTRATION_ERRORS = "org.onepf.opfpush.intent.EXTRA_REGISTRATION_ERRORS"; // // public static final String ACTION_NO_AVAILABLE_PROVIDER = "org.onepf.opfpush.intent.NO_AVAILABLE_PROVIDER"; // public static final String ACTION_RECEIVE = "org.onepf.opfpush.intent.RECEIVE"; // public static final String ACTION_REGISTRATION = "org.onepf.opfpush.intent.REGISTRATION"; // public static final String ACTION_UNREGISTRATION = "org.onepf.opfpush.intent.UNREGISTRATION"; // // public static final String ACTION_RETRY_REGISTER = BuildConfig.APPLICATION_ID + "intent.RETRY_REGISTER"; // public static final String ACTION_RETRY_UNREGISTER = BuildConfig.APPLICATION_ID + "intent.RETRY_UNREGISTER"; // // static final String ACTION_CHECK_REGISTERING_TIMEOUT = BuildConfig.APPLICATION_ID + "intent.CHECK_REGISTERING_TIMEOUT"; // // static final String PACKAGE_DATA_SCHEME = "package"; // // private OPFConstants() { // throw new UnsupportedOperationException(); // } // } // // Path: opfpush/src/main/java/org/onepf/opfpush/OPFPush.java // public final class OPFPush { // // private static volatile OPFPushHelper helper; // // private OPFPush() { // throw new UnsupportedOperationException(); // } // // /** // * Returns the {@link org.onepf.opfpush.OPFPushHelper} instance. // * // * @return The {@link org.onepf.opfpush.OPFPushHelper} instance. // * @throws org.onepf.opfutils.exception.InitException If {@code OPFPush} wasn't initialized. // */ // @NonNull // public static OPFPushHelper getHelper() { // OPFLog.logMethod(); // if (helper == null) { // throw new InitException(false); // } // return helper; // } // // /** // * Initializes the OPFPush library and creates the {@link org.onepf.opfpush.OPFPushHelper} singleton instance. // * // * @param context The {@link android.content.Context} instance. // * @param configuration The {@link org.onepf.opfpush.configuration.Configuration} instance. // * @throws org.onepf.opfutils.exception.WrongThreadException If this method is not called from the main thread. // * @throws org.onepf.opfutils.exception.InitException If the {@code OPFPush} has already been initialized. // */ // public static void init(@NonNull final Context context, // @NonNull final Configuration configuration) { // OPFLog.logMethod(context, configuration); // OPFChecks.checkThread(true); // // if (helper != null) { // throw new InitException(true); // } // // if (OPFUtils.isMainProcess(context)) { // OPFLog.i("Init in main process"); // final OPFPushHelper newHelper = new OPFPushHelperImpl(context); // newHelper.init(configuration); // helper = newHelper; // } else { // OPFLog.i("Init in not main process"); // helper = new OPFPushHelperStub(); // } // } // } // // Path: opfpush-providers/gcm/src/main/java/org/onepf/opfpush/gcm/GCMConstants.java // public static final String PROVIDER_NAME = "Google Cloud Messaging";
import android.os.Bundle; import android.support.annotation.NonNull; import com.google.android.gms.gcm.GcmListenerService; import org.onepf.opfpush.OPFConstants; import org.onepf.opfpush.OPFPush; import org.onepf.opfutils.OPFLog; import org.onepf.opfutils.OPFUtils; import static org.onepf.opfpush.gcm.GCMConstants.PROVIDER_NAME;
/* * Copyright 2012-2015 One Platform Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onepf.opfpush.gcm; /** * @author Roman Savin * @since 16.06.2015 */ public class GCMService extends GcmListenerService { @Override public void onMessageReceived(@NonNull final String from, @NonNull final Bundle data) { OPFLog.logMethod(from, OPFUtils.toString(data));
// Path: opfpush/src/main/java/org/onepf/opfpush/OPFConstants.java // public final class OPFConstants { // // /** // * Indicates unknown count of deleted messages. // */ // public static final int MESSAGES_COUNT_UNKNOWN = Integer.MIN_VALUE; // // public static final String EXTRA_PROVIDER_NAME = "org.onepf.opfpush.intent.EXTRA_PROVIDER_NAME"; // public static final String EXTRA_REGISTRATION_ID = "org.onepf.opfpush.intent.EXTRA_REGISTRATION_ID"; // public static final String EXTRA_MESSAGE_TYPE = "org.onepf.opfpush.intent.EXTRA_MESSAGE_TYPE"; // public static final String EXTRA_MESSAGE_COUNT = "org.onepf.opfpush.intent.EXTRA_MESSAGE_COUNT"; // public static final String EXTRA_REGISTRATION_ERRORS = "org.onepf.opfpush.intent.EXTRA_REGISTRATION_ERRORS"; // // public static final String ACTION_NO_AVAILABLE_PROVIDER = "org.onepf.opfpush.intent.NO_AVAILABLE_PROVIDER"; // public static final String ACTION_RECEIVE = "org.onepf.opfpush.intent.RECEIVE"; // public static final String ACTION_REGISTRATION = "org.onepf.opfpush.intent.REGISTRATION"; // public static final String ACTION_UNREGISTRATION = "org.onepf.opfpush.intent.UNREGISTRATION"; // // public static final String ACTION_RETRY_REGISTER = BuildConfig.APPLICATION_ID + "intent.RETRY_REGISTER"; // public static final String ACTION_RETRY_UNREGISTER = BuildConfig.APPLICATION_ID + "intent.RETRY_UNREGISTER"; // // static final String ACTION_CHECK_REGISTERING_TIMEOUT = BuildConfig.APPLICATION_ID + "intent.CHECK_REGISTERING_TIMEOUT"; // // static final String PACKAGE_DATA_SCHEME = "package"; // // private OPFConstants() { // throw new UnsupportedOperationException(); // } // } // // Path: opfpush/src/main/java/org/onepf/opfpush/OPFPush.java // public final class OPFPush { // // private static volatile OPFPushHelper helper; // // private OPFPush() { // throw new UnsupportedOperationException(); // } // // /** // * Returns the {@link org.onepf.opfpush.OPFPushHelper} instance. // * // * @return The {@link org.onepf.opfpush.OPFPushHelper} instance. // * @throws org.onepf.opfutils.exception.InitException If {@code OPFPush} wasn't initialized. // */ // @NonNull // public static OPFPushHelper getHelper() { // OPFLog.logMethod(); // if (helper == null) { // throw new InitException(false); // } // return helper; // } // // /** // * Initializes the OPFPush library and creates the {@link org.onepf.opfpush.OPFPushHelper} singleton instance. // * // * @param context The {@link android.content.Context} instance. // * @param configuration The {@link org.onepf.opfpush.configuration.Configuration} instance. // * @throws org.onepf.opfutils.exception.WrongThreadException If this method is not called from the main thread. // * @throws org.onepf.opfutils.exception.InitException If the {@code OPFPush} has already been initialized. // */ // public static void init(@NonNull final Context context, // @NonNull final Configuration configuration) { // OPFLog.logMethod(context, configuration); // OPFChecks.checkThread(true); // // if (helper != null) { // throw new InitException(true); // } // // if (OPFUtils.isMainProcess(context)) { // OPFLog.i("Init in main process"); // final OPFPushHelper newHelper = new OPFPushHelperImpl(context); // newHelper.init(configuration); // helper = newHelper; // } else { // OPFLog.i("Init in not main process"); // helper = new OPFPushHelperStub(); // } // } // } // // Path: opfpush-providers/gcm/src/main/java/org/onepf/opfpush/gcm/GCMConstants.java // public static final String PROVIDER_NAME = "Google Cloud Messaging"; // Path: opfpush-providers/gcm/src/main/java/org/onepf/opfpush/gcm/GCMService.java import android.os.Bundle; import android.support.annotation.NonNull; import com.google.android.gms.gcm.GcmListenerService; import org.onepf.opfpush.OPFConstants; import org.onepf.opfpush.OPFPush; import org.onepf.opfutils.OPFLog; import org.onepf.opfutils.OPFUtils; import static org.onepf.opfpush.gcm.GCMConstants.PROVIDER_NAME; /* * Copyright 2012-2015 One Platform Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onepf.opfpush.gcm; /** * @author Roman Savin * @since 16.06.2015 */ public class GCMService extends GcmListenerService { @Override public void onMessageReceived(@NonNull final String from, @NonNull final Bundle data) { OPFLog.logMethod(from, OPFUtils.toString(data));
OPFPush.getHelper().getReceivedMessageHandler().onMessage(PROVIDER_NAME, data);
onepf/OPFPush
opfpush-providers/gcm/src/main/java/org/onepf/opfpush/gcm/GCMService.java
// Path: opfpush/src/main/java/org/onepf/opfpush/OPFConstants.java // public final class OPFConstants { // // /** // * Indicates unknown count of deleted messages. // */ // public static final int MESSAGES_COUNT_UNKNOWN = Integer.MIN_VALUE; // // public static final String EXTRA_PROVIDER_NAME = "org.onepf.opfpush.intent.EXTRA_PROVIDER_NAME"; // public static final String EXTRA_REGISTRATION_ID = "org.onepf.opfpush.intent.EXTRA_REGISTRATION_ID"; // public static final String EXTRA_MESSAGE_TYPE = "org.onepf.opfpush.intent.EXTRA_MESSAGE_TYPE"; // public static final String EXTRA_MESSAGE_COUNT = "org.onepf.opfpush.intent.EXTRA_MESSAGE_COUNT"; // public static final String EXTRA_REGISTRATION_ERRORS = "org.onepf.opfpush.intent.EXTRA_REGISTRATION_ERRORS"; // // public static final String ACTION_NO_AVAILABLE_PROVIDER = "org.onepf.opfpush.intent.NO_AVAILABLE_PROVIDER"; // public static final String ACTION_RECEIVE = "org.onepf.opfpush.intent.RECEIVE"; // public static final String ACTION_REGISTRATION = "org.onepf.opfpush.intent.REGISTRATION"; // public static final String ACTION_UNREGISTRATION = "org.onepf.opfpush.intent.UNREGISTRATION"; // // public static final String ACTION_RETRY_REGISTER = BuildConfig.APPLICATION_ID + "intent.RETRY_REGISTER"; // public static final String ACTION_RETRY_UNREGISTER = BuildConfig.APPLICATION_ID + "intent.RETRY_UNREGISTER"; // // static final String ACTION_CHECK_REGISTERING_TIMEOUT = BuildConfig.APPLICATION_ID + "intent.CHECK_REGISTERING_TIMEOUT"; // // static final String PACKAGE_DATA_SCHEME = "package"; // // private OPFConstants() { // throw new UnsupportedOperationException(); // } // } // // Path: opfpush/src/main/java/org/onepf/opfpush/OPFPush.java // public final class OPFPush { // // private static volatile OPFPushHelper helper; // // private OPFPush() { // throw new UnsupportedOperationException(); // } // // /** // * Returns the {@link org.onepf.opfpush.OPFPushHelper} instance. // * // * @return The {@link org.onepf.opfpush.OPFPushHelper} instance. // * @throws org.onepf.opfutils.exception.InitException If {@code OPFPush} wasn't initialized. // */ // @NonNull // public static OPFPushHelper getHelper() { // OPFLog.logMethod(); // if (helper == null) { // throw new InitException(false); // } // return helper; // } // // /** // * Initializes the OPFPush library and creates the {@link org.onepf.opfpush.OPFPushHelper} singleton instance. // * // * @param context The {@link android.content.Context} instance. // * @param configuration The {@link org.onepf.opfpush.configuration.Configuration} instance. // * @throws org.onepf.opfutils.exception.WrongThreadException If this method is not called from the main thread. // * @throws org.onepf.opfutils.exception.InitException If the {@code OPFPush} has already been initialized. // */ // public static void init(@NonNull final Context context, // @NonNull final Configuration configuration) { // OPFLog.logMethod(context, configuration); // OPFChecks.checkThread(true); // // if (helper != null) { // throw new InitException(true); // } // // if (OPFUtils.isMainProcess(context)) { // OPFLog.i("Init in main process"); // final OPFPushHelper newHelper = new OPFPushHelperImpl(context); // newHelper.init(configuration); // helper = newHelper; // } else { // OPFLog.i("Init in not main process"); // helper = new OPFPushHelperStub(); // } // } // } // // Path: opfpush-providers/gcm/src/main/java/org/onepf/opfpush/gcm/GCMConstants.java // public static final String PROVIDER_NAME = "Google Cloud Messaging";
import android.os.Bundle; import android.support.annotation.NonNull; import com.google.android.gms.gcm.GcmListenerService; import org.onepf.opfpush.OPFConstants; import org.onepf.opfpush.OPFPush; import org.onepf.opfutils.OPFLog; import org.onepf.opfutils.OPFUtils; import static org.onepf.opfpush.gcm.GCMConstants.PROVIDER_NAME;
/* * Copyright 2012-2015 One Platform Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onepf.opfpush.gcm; /** * @author Roman Savin * @since 16.06.2015 */ public class GCMService extends GcmListenerService { @Override public void onMessageReceived(@NonNull final String from, @NonNull final Bundle data) { OPFLog.logMethod(from, OPFUtils.toString(data));
// Path: opfpush/src/main/java/org/onepf/opfpush/OPFConstants.java // public final class OPFConstants { // // /** // * Indicates unknown count of deleted messages. // */ // public static final int MESSAGES_COUNT_UNKNOWN = Integer.MIN_VALUE; // // public static final String EXTRA_PROVIDER_NAME = "org.onepf.opfpush.intent.EXTRA_PROVIDER_NAME"; // public static final String EXTRA_REGISTRATION_ID = "org.onepf.opfpush.intent.EXTRA_REGISTRATION_ID"; // public static final String EXTRA_MESSAGE_TYPE = "org.onepf.opfpush.intent.EXTRA_MESSAGE_TYPE"; // public static final String EXTRA_MESSAGE_COUNT = "org.onepf.opfpush.intent.EXTRA_MESSAGE_COUNT"; // public static final String EXTRA_REGISTRATION_ERRORS = "org.onepf.opfpush.intent.EXTRA_REGISTRATION_ERRORS"; // // public static final String ACTION_NO_AVAILABLE_PROVIDER = "org.onepf.opfpush.intent.NO_AVAILABLE_PROVIDER"; // public static final String ACTION_RECEIVE = "org.onepf.opfpush.intent.RECEIVE"; // public static final String ACTION_REGISTRATION = "org.onepf.opfpush.intent.REGISTRATION"; // public static final String ACTION_UNREGISTRATION = "org.onepf.opfpush.intent.UNREGISTRATION"; // // public static final String ACTION_RETRY_REGISTER = BuildConfig.APPLICATION_ID + "intent.RETRY_REGISTER"; // public static final String ACTION_RETRY_UNREGISTER = BuildConfig.APPLICATION_ID + "intent.RETRY_UNREGISTER"; // // static final String ACTION_CHECK_REGISTERING_TIMEOUT = BuildConfig.APPLICATION_ID + "intent.CHECK_REGISTERING_TIMEOUT"; // // static final String PACKAGE_DATA_SCHEME = "package"; // // private OPFConstants() { // throw new UnsupportedOperationException(); // } // } // // Path: opfpush/src/main/java/org/onepf/opfpush/OPFPush.java // public final class OPFPush { // // private static volatile OPFPushHelper helper; // // private OPFPush() { // throw new UnsupportedOperationException(); // } // // /** // * Returns the {@link org.onepf.opfpush.OPFPushHelper} instance. // * // * @return The {@link org.onepf.opfpush.OPFPushHelper} instance. // * @throws org.onepf.opfutils.exception.InitException If {@code OPFPush} wasn't initialized. // */ // @NonNull // public static OPFPushHelper getHelper() { // OPFLog.logMethod(); // if (helper == null) { // throw new InitException(false); // } // return helper; // } // // /** // * Initializes the OPFPush library and creates the {@link org.onepf.opfpush.OPFPushHelper} singleton instance. // * // * @param context The {@link android.content.Context} instance. // * @param configuration The {@link org.onepf.opfpush.configuration.Configuration} instance. // * @throws org.onepf.opfutils.exception.WrongThreadException If this method is not called from the main thread. // * @throws org.onepf.opfutils.exception.InitException If the {@code OPFPush} has already been initialized. // */ // public static void init(@NonNull final Context context, // @NonNull final Configuration configuration) { // OPFLog.logMethod(context, configuration); // OPFChecks.checkThread(true); // // if (helper != null) { // throw new InitException(true); // } // // if (OPFUtils.isMainProcess(context)) { // OPFLog.i("Init in main process"); // final OPFPushHelper newHelper = new OPFPushHelperImpl(context); // newHelper.init(configuration); // helper = newHelper; // } else { // OPFLog.i("Init in not main process"); // helper = new OPFPushHelperStub(); // } // } // } // // Path: opfpush-providers/gcm/src/main/java/org/onepf/opfpush/gcm/GCMConstants.java // public static final String PROVIDER_NAME = "Google Cloud Messaging"; // Path: opfpush-providers/gcm/src/main/java/org/onepf/opfpush/gcm/GCMService.java import android.os.Bundle; import android.support.annotation.NonNull; import com.google.android.gms.gcm.GcmListenerService; import org.onepf.opfpush.OPFConstants; import org.onepf.opfpush.OPFPush; import org.onepf.opfutils.OPFLog; import org.onepf.opfutils.OPFUtils; import static org.onepf.opfpush.gcm.GCMConstants.PROVIDER_NAME; /* * Copyright 2012-2015 One Platform Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onepf.opfpush.gcm; /** * @author Roman Savin * @since 16.06.2015 */ public class GCMService extends GcmListenerService { @Override public void onMessageReceived(@NonNull final String from, @NonNull final Bundle data) { OPFLog.logMethod(from, OPFUtils.toString(data));
OPFPush.getHelper().getReceivedMessageHandler().onMessage(PROVIDER_NAME, data);
onepf/OPFPush
opfpush-providers/gcm/src/main/java/org/onepf/opfpush/gcm/GCMService.java
// Path: opfpush/src/main/java/org/onepf/opfpush/OPFConstants.java // public final class OPFConstants { // // /** // * Indicates unknown count of deleted messages. // */ // public static final int MESSAGES_COUNT_UNKNOWN = Integer.MIN_VALUE; // // public static final String EXTRA_PROVIDER_NAME = "org.onepf.opfpush.intent.EXTRA_PROVIDER_NAME"; // public static final String EXTRA_REGISTRATION_ID = "org.onepf.opfpush.intent.EXTRA_REGISTRATION_ID"; // public static final String EXTRA_MESSAGE_TYPE = "org.onepf.opfpush.intent.EXTRA_MESSAGE_TYPE"; // public static final String EXTRA_MESSAGE_COUNT = "org.onepf.opfpush.intent.EXTRA_MESSAGE_COUNT"; // public static final String EXTRA_REGISTRATION_ERRORS = "org.onepf.opfpush.intent.EXTRA_REGISTRATION_ERRORS"; // // public static final String ACTION_NO_AVAILABLE_PROVIDER = "org.onepf.opfpush.intent.NO_AVAILABLE_PROVIDER"; // public static final String ACTION_RECEIVE = "org.onepf.opfpush.intent.RECEIVE"; // public static final String ACTION_REGISTRATION = "org.onepf.opfpush.intent.REGISTRATION"; // public static final String ACTION_UNREGISTRATION = "org.onepf.opfpush.intent.UNREGISTRATION"; // // public static final String ACTION_RETRY_REGISTER = BuildConfig.APPLICATION_ID + "intent.RETRY_REGISTER"; // public static final String ACTION_RETRY_UNREGISTER = BuildConfig.APPLICATION_ID + "intent.RETRY_UNREGISTER"; // // static final String ACTION_CHECK_REGISTERING_TIMEOUT = BuildConfig.APPLICATION_ID + "intent.CHECK_REGISTERING_TIMEOUT"; // // static final String PACKAGE_DATA_SCHEME = "package"; // // private OPFConstants() { // throw new UnsupportedOperationException(); // } // } // // Path: opfpush/src/main/java/org/onepf/opfpush/OPFPush.java // public final class OPFPush { // // private static volatile OPFPushHelper helper; // // private OPFPush() { // throw new UnsupportedOperationException(); // } // // /** // * Returns the {@link org.onepf.opfpush.OPFPushHelper} instance. // * // * @return The {@link org.onepf.opfpush.OPFPushHelper} instance. // * @throws org.onepf.opfutils.exception.InitException If {@code OPFPush} wasn't initialized. // */ // @NonNull // public static OPFPushHelper getHelper() { // OPFLog.logMethod(); // if (helper == null) { // throw new InitException(false); // } // return helper; // } // // /** // * Initializes the OPFPush library and creates the {@link org.onepf.opfpush.OPFPushHelper} singleton instance. // * // * @param context The {@link android.content.Context} instance. // * @param configuration The {@link org.onepf.opfpush.configuration.Configuration} instance. // * @throws org.onepf.opfutils.exception.WrongThreadException If this method is not called from the main thread. // * @throws org.onepf.opfutils.exception.InitException If the {@code OPFPush} has already been initialized. // */ // public static void init(@NonNull final Context context, // @NonNull final Configuration configuration) { // OPFLog.logMethod(context, configuration); // OPFChecks.checkThread(true); // // if (helper != null) { // throw new InitException(true); // } // // if (OPFUtils.isMainProcess(context)) { // OPFLog.i("Init in main process"); // final OPFPushHelper newHelper = new OPFPushHelperImpl(context); // newHelper.init(configuration); // helper = newHelper; // } else { // OPFLog.i("Init in not main process"); // helper = new OPFPushHelperStub(); // } // } // } // // Path: opfpush-providers/gcm/src/main/java/org/onepf/opfpush/gcm/GCMConstants.java // public static final String PROVIDER_NAME = "Google Cloud Messaging";
import android.os.Bundle; import android.support.annotation.NonNull; import com.google.android.gms.gcm.GcmListenerService; import org.onepf.opfpush.OPFConstants; import org.onepf.opfpush.OPFPush; import org.onepf.opfutils.OPFLog; import org.onepf.opfutils.OPFUtils; import static org.onepf.opfpush.gcm.GCMConstants.PROVIDER_NAME;
/* * Copyright 2012-2015 One Platform Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onepf.opfpush.gcm; /** * @author Roman Savin * @since 16.06.2015 */ public class GCMService extends GcmListenerService { @Override public void onMessageReceived(@NonNull final String from, @NonNull final Bundle data) { OPFLog.logMethod(from, OPFUtils.toString(data)); OPFPush.getHelper().getReceivedMessageHandler().onMessage(PROVIDER_NAME, data); } @Override public void onDeletedMessages() { OPFLog.logMethod(); OPFPush.getHelper().getReceivedMessageHandler()
// Path: opfpush/src/main/java/org/onepf/opfpush/OPFConstants.java // public final class OPFConstants { // // /** // * Indicates unknown count of deleted messages. // */ // public static final int MESSAGES_COUNT_UNKNOWN = Integer.MIN_VALUE; // // public static final String EXTRA_PROVIDER_NAME = "org.onepf.opfpush.intent.EXTRA_PROVIDER_NAME"; // public static final String EXTRA_REGISTRATION_ID = "org.onepf.opfpush.intent.EXTRA_REGISTRATION_ID"; // public static final String EXTRA_MESSAGE_TYPE = "org.onepf.opfpush.intent.EXTRA_MESSAGE_TYPE"; // public static final String EXTRA_MESSAGE_COUNT = "org.onepf.opfpush.intent.EXTRA_MESSAGE_COUNT"; // public static final String EXTRA_REGISTRATION_ERRORS = "org.onepf.opfpush.intent.EXTRA_REGISTRATION_ERRORS"; // // public static final String ACTION_NO_AVAILABLE_PROVIDER = "org.onepf.opfpush.intent.NO_AVAILABLE_PROVIDER"; // public static final String ACTION_RECEIVE = "org.onepf.opfpush.intent.RECEIVE"; // public static final String ACTION_REGISTRATION = "org.onepf.opfpush.intent.REGISTRATION"; // public static final String ACTION_UNREGISTRATION = "org.onepf.opfpush.intent.UNREGISTRATION"; // // public static final String ACTION_RETRY_REGISTER = BuildConfig.APPLICATION_ID + "intent.RETRY_REGISTER"; // public static final String ACTION_RETRY_UNREGISTER = BuildConfig.APPLICATION_ID + "intent.RETRY_UNREGISTER"; // // static final String ACTION_CHECK_REGISTERING_TIMEOUT = BuildConfig.APPLICATION_ID + "intent.CHECK_REGISTERING_TIMEOUT"; // // static final String PACKAGE_DATA_SCHEME = "package"; // // private OPFConstants() { // throw new UnsupportedOperationException(); // } // } // // Path: opfpush/src/main/java/org/onepf/opfpush/OPFPush.java // public final class OPFPush { // // private static volatile OPFPushHelper helper; // // private OPFPush() { // throw new UnsupportedOperationException(); // } // // /** // * Returns the {@link org.onepf.opfpush.OPFPushHelper} instance. // * // * @return The {@link org.onepf.opfpush.OPFPushHelper} instance. // * @throws org.onepf.opfutils.exception.InitException If {@code OPFPush} wasn't initialized. // */ // @NonNull // public static OPFPushHelper getHelper() { // OPFLog.logMethod(); // if (helper == null) { // throw new InitException(false); // } // return helper; // } // // /** // * Initializes the OPFPush library and creates the {@link org.onepf.opfpush.OPFPushHelper} singleton instance. // * // * @param context The {@link android.content.Context} instance. // * @param configuration The {@link org.onepf.opfpush.configuration.Configuration} instance. // * @throws org.onepf.opfutils.exception.WrongThreadException If this method is not called from the main thread. // * @throws org.onepf.opfutils.exception.InitException If the {@code OPFPush} has already been initialized. // */ // public static void init(@NonNull final Context context, // @NonNull final Configuration configuration) { // OPFLog.logMethod(context, configuration); // OPFChecks.checkThread(true); // // if (helper != null) { // throw new InitException(true); // } // // if (OPFUtils.isMainProcess(context)) { // OPFLog.i("Init in main process"); // final OPFPushHelper newHelper = new OPFPushHelperImpl(context); // newHelper.init(configuration); // helper = newHelper; // } else { // OPFLog.i("Init in not main process"); // helper = new OPFPushHelperStub(); // } // } // } // // Path: opfpush-providers/gcm/src/main/java/org/onepf/opfpush/gcm/GCMConstants.java // public static final String PROVIDER_NAME = "Google Cloud Messaging"; // Path: opfpush-providers/gcm/src/main/java/org/onepf/opfpush/gcm/GCMService.java import android.os.Bundle; import android.support.annotation.NonNull; import com.google.android.gms.gcm.GcmListenerService; import org.onepf.opfpush.OPFConstants; import org.onepf.opfpush.OPFPush; import org.onepf.opfutils.OPFLog; import org.onepf.opfutils.OPFUtils; import static org.onepf.opfpush.gcm.GCMConstants.PROVIDER_NAME; /* * Copyright 2012-2015 One Platform Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onepf.opfpush.gcm; /** * @author Roman Savin * @since 16.06.2015 */ public class GCMService extends GcmListenerService { @Override public void onMessageReceived(@NonNull final String from, @NonNull final Bundle data) { OPFLog.logMethod(from, OPFUtils.toString(data)); OPFPush.getHelper().getReceivedMessageHandler().onMessage(PROVIDER_NAME, data); } @Override public void onDeletedMessages() { OPFLog.logMethod(); OPFPush.getHelper().getReceivedMessageHandler()
.onDeletedMessages(PROVIDER_NAME, OPFConstants.MESSAGES_COUNT_UNKNOWN);
onepf/OPFPush
samples/pushchat/src/main/java/org/onepf/pushchat/retrofit/PushService.java
// Path: samples/pushchat/src/main/java/org/onepf/pushchat/model/request/RegistrationRequestBody.java // public final class RegistrationRequestBody extends RequestBody { // // @SerializedName("providerName") // @NonNull // public final String providerName; // // @SerializedName("registrationId") // @NonNull // public final String registrationId; // // public RegistrationRequestBody(@NonNull final String uuid, // @NonNull final String providerName, // @NonNull final String registrationId) { // super(uuid); // this.providerName = providerName; // this.registrationId = registrationId; // } // } // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/model/request/SubscribeOrUnsubscribeRequestBody.java // public final class SubscribeOrUnsubscribeRequestBody { // // @NonNull // public final String topic; // // @NonNull // public final String uuid; // // public SubscribeOrUnsubscribeRequestBody(@NonNull final String topic, @NonNull final String uuid) { // this.topic = topic; // this.uuid = uuid; // } // } // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/model/request/UnregistrationRequestBody.java // public final class UnregistrationRequestBody extends RequestBody { // // public UnregistrationRequestBody(@NonNull final String uuid) { // super(uuid); // } // } // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/model/request/push/PushMessageRequestBody.java // public final class PushMessageRequestBody { // // @SerializedName("uuids") // public final Set<String> uuids; // // @SerializedName("sender") // public final String sender; // // @SerializedName("message") // @NonNull // public final String message; // // public PushMessageRequestBody(@NonNull final Set<String> uuids, // @NonNull final String sender, // @NonNull final String message) { // this.uuids = uuids; // this.sender = sender; // this.message = message; // } // } // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/model/response/ExistResponse.java // public final class ExistResponse { // // @SerializedName("exist") // public final boolean exist; // // public ExistResponse(final boolean exist) { // this.exist = exist; // } // } // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/model/response/RegistrationResponse.java // public final class RegistrationResponse { // // @NonNull // public final String uuid; // // @NonNull // public final String providerName; // // @NonNull // public final String registrationId; // // public RegistrationResponse(@NonNull final String uuid, // @NonNull final String providerName, // @NonNull final String registrationId) { // this.uuid = uuid; // this.providerName = providerName; // this.registrationId = registrationId; // } // } // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/model/response/TopicsResponse.java // public final class TopicsResponse { // // @SerializedName("topics") // @Nullable // public final List<String> topics; // // public TopicsResponse(@Nullable final List<String> topics) { // this.topics = topics; // } // } // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/model/response/UnregistrationResponse.java // public final class UnregistrationResponse { // // @NonNull // public final String uuid; // // @Nullable // public final String providerName; // // @Nullable // public final String registrationId; // // public UnregistrationResponse(@NonNull final String uuid, // @Nullable final String providerName, // @Nullable final String registrationId) { // this.uuid = uuid; // this.providerName = providerName; // this.registrationId = registrationId; // } // } // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/model/response/push/PushMessageResponse.java // public final class PushMessageResponse { // // @Nullable // public final PushResult[] successed; // // @Nullable // public final FailedPushResult[] failed; // // @NonNull // public final String message; // // public PushMessageResponse(@Nullable final PushResult[] successed, // @Nullable final FailedPushResult[] failed, // @NonNull final String message) { // this.successed = successed; // this.failed = failed; // this.message = message; // } // }
import retrofit.http.GET; import retrofit.http.POST; import retrofit.http.Query; import android.support.annotation.NonNull; import org.onepf.pushchat.model.request.RegistrationRequestBody; import org.onepf.pushchat.model.request.SubscribeOrUnsubscribeRequestBody; import org.onepf.pushchat.model.request.UnregistrationRequestBody; import org.onepf.pushchat.model.request.push.PushMessageRequestBody; import org.onepf.pushchat.model.response.ExistResponse; import org.onepf.pushchat.model.response.RegistrationResponse; import org.onepf.pushchat.model.response.TopicsResponse; import org.onepf.pushchat.model.response.UnregistrationResponse; import org.onepf.pushchat.model.response.push.PushMessageResponse; import retrofit.Callback; import retrofit.http.Body;
/* * Copyright 2012-2015 One Platform Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onepf.pushchat.retrofit; /** * @author Roman Savin * @since 19.04.2015 */ public interface PushService { @POST("/register")
// Path: samples/pushchat/src/main/java/org/onepf/pushchat/model/request/RegistrationRequestBody.java // public final class RegistrationRequestBody extends RequestBody { // // @SerializedName("providerName") // @NonNull // public final String providerName; // // @SerializedName("registrationId") // @NonNull // public final String registrationId; // // public RegistrationRequestBody(@NonNull final String uuid, // @NonNull final String providerName, // @NonNull final String registrationId) { // super(uuid); // this.providerName = providerName; // this.registrationId = registrationId; // } // } // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/model/request/SubscribeOrUnsubscribeRequestBody.java // public final class SubscribeOrUnsubscribeRequestBody { // // @NonNull // public final String topic; // // @NonNull // public final String uuid; // // public SubscribeOrUnsubscribeRequestBody(@NonNull final String topic, @NonNull final String uuid) { // this.topic = topic; // this.uuid = uuid; // } // } // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/model/request/UnregistrationRequestBody.java // public final class UnregistrationRequestBody extends RequestBody { // // public UnregistrationRequestBody(@NonNull final String uuid) { // super(uuid); // } // } // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/model/request/push/PushMessageRequestBody.java // public final class PushMessageRequestBody { // // @SerializedName("uuids") // public final Set<String> uuids; // // @SerializedName("sender") // public final String sender; // // @SerializedName("message") // @NonNull // public final String message; // // public PushMessageRequestBody(@NonNull final Set<String> uuids, // @NonNull final String sender, // @NonNull final String message) { // this.uuids = uuids; // this.sender = sender; // this.message = message; // } // } // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/model/response/ExistResponse.java // public final class ExistResponse { // // @SerializedName("exist") // public final boolean exist; // // public ExistResponse(final boolean exist) { // this.exist = exist; // } // } // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/model/response/RegistrationResponse.java // public final class RegistrationResponse { // // @NonNull // public final String uuid; // // @NonNull // public final String providerName; // // @NonNull // public final String registrationId; // // public RegistrationResponse(@NonNull final String uuid, // @NonNull final String providerName, // @NonNull final String registrationId) { // this.uuid = uuid; // this.providerName = providerName; // this.registrationId = registrationId; // } // } // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/model/response/TopicsResponse.java // public final class TopicsResponse { // // @SerializedName("topics") // @Nullable // public final List<String> topics; // // public TopicsResponse(@Nullable final List<String> topics) { // this.topics = topics; // } // } // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/model/response/UnregistrationResponse.java // public final class UnregistrationResponse { // // @NonNull // public final String uuid; // // @Nullable // public final String providerName; // // @Nullable // public final String registrationId; // // public UnregistrationResponse(@NonNull final String uuid, // @Nullable final String providerName, // @Nullable final String registrationId) { // this.uuid = uuid; // this.providerName = providerName; // this.registrationId = registrationId; // } // } // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/model/response/push/PushMessageResponse.java // public final class PushMessageResponse { // // @Nullable // public final PushResult[] successed; // // @Nullable // public final FailedPushResult[] failed; // // @NonNull // public final String message; // // public PushMessageResponse(@Nullable final PushResult[] successed, // @Nullable final FailedPushResult[] failed, // @NonNull final String message) { // this.successed = successed; // this.failed = failed; // this.message = message; // } // } // Path: samples/pushchat/src/main/java/org/onepf/pushchat/retrofit/PushService.java import retrofit.http.GET; import retrofit.http.POST; import retrofit.http.Query; import android.support.annotation.NonNull; import org.onepf.pushchat.model.request.RegistrationRequestBody; import org.onepf.pushchat.model.request.SubscribeOrUnsubscribeRequestBody; import org.onepf.pushchat.model.request.UnregistrationRequestBody; import org.onepf.pushchat.model.request.push.PushMessageRequestBody; import org.onepf.pushchat.model.response.ExistResponse; import org.onepf.pushchat.model.response.RegistrationResponse; import org.onepf.pushchat.model.response.TopicsResponse; import org.onepf.pushchat.model.response.UnregistrationResponse; import org.onepf.pushchat.model.response.push.PushMessageResponse; import retrofit.Callback; import retrofit.http.Body; /* * Copyright 2012-2015 One Platform Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onepf.pushchat.retrofit; /** * @author Roman Savin * @since 19.04.2015 */ public interface PushService { @POST("/register")
void register(@Body @NonNull final RegistrationRequestBody body,
onepf/OPFPush
samples/pushchat/src/main/java/org/onepf/pushchat/retrofit/PushService.java
// Path: samples/pushchat/src/main/java/org/onepf/pushchat/model/request/RegistrationRequestBody.java // public final class RegistrationRequestBody extends RequestBody { // // @SerializedName("providerName") // @NonNull // public final String providerName; // // @SerializedName("registrationId") // @NonNull // public final String registrationId; // // public RegistrationRequestBody(@NonNull final String uuid, // @NonNull final String providerName, // @NonNull final String registrationId) { // super(uuid); // this.providerName = providerName; // this.registrationId = registrationId; // } // } // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/model/request/SubscribeOrUnsubscribeRequestBody.java // public final class SubscribeOrUnsubscribeRequestBody { // // @NonNull // public final String topic; // // @NonNull // public final String uuid; // // public SubscribeOrUnsubscribeRequestBody(@NonNull final String topic, @NonNull final String uuid) { // this.topic = topic; // this.uuid = uuid; // } // } // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/model/request/UnregistrationRequestBody.java // public final class UnregistrationRequestBody extends RequestBody { // // public UnregistrationRequestBody(@NonNull final String uuid) { // super(uuid); // } // } // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/model/request/push/PushMessageRequestBody.java // public final class PushMessageRequestBody { // // @SerializedName("uuids") // public final Set<String> uuids; // // @SerializedName("sender") // public final String sender; // // @SerializedName("message") // @NonNull // public final String message; // // public PushMessageRequestBody(@NonNull final Set<String> uuids, // @NonNull final String sender, // @NonNull final String message) { // this.uuids = uuids; // this.sender = sender; // this.message = message; // } // } // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/model/response/ExistResponse.java // public final class ExistResponse { // // @SerializedName("exist") // public final boolean exist; // // public ExistResponse(final boolean exist) { // this.exist = exist; // } // } // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/model/response/RegistrationResponse.java // public final class RegistrationResponse { // // @NonNull // public final String uuid; // // @NonNull // public final String providerName; // // @NonNull // public final String registrationId; // // public RegistrationResponse(@NonNull final String uuid, // @NonNull final String providerName, // @NonNull final String registrationId) { // this.uuid = uuid; // this.providerName = providerName; // this.registrationId = registrationId; // } // } // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/model/response/TopicsResponse.java // public final class TopicsResponse { // // @SerializedName("topics") // @Nullable // public final List<String> topics; // // public TopicsResponse(@Nullable final List<String> topics) { // this.topics = topics; // } // } // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/model/response/UnregistrationResponse.java // public final class UnregistrationResponse { // // @NonNull // public final String uuid; // // @Nullable // public final String providerName; // // @Nullable // public final String registrationId; // // public UnregistrationResponse(@NonNull final String uuid, // @Nullable final String providerName, // @Nullable final String registrationId) { // this.uuid = uuid; // this.providerName = providerName; // this.registrationId = registrationId; // } // } // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/model/response/push/PushMessageResponse.java // public final class PushMessageResponse { // // @Nullable // public final PushResult[] successed; // // @Nullable // public final FailedPushResult[] failed; // // @NonNull // public final String message; // // public PushMessageResponse(@Nullable final PushResult[] successed, // @Nullable final FailedPushResult[] failed, // @NonNull final String message) { // this.successed = successed; // this.failed = failed; // this.message = message; // } // }
import retrofit.http.GET; import retrofit.http.POST; import retrofit.http.Query; import android.support.annotation.NonNull; import org.onepf.pushchat.model.request.RegistrationRequestBody; import org.onepf.pushchat.model.request.SubscribeOrUnsubscribeRequestBody; import org.onepf.pushchat.model.request.UnregistrationRequestBody; import org.onepf.pushchat.model.request.push.PushMessageRequestBody; import org.onepf.pushchat.model.response.ExistResponse; import org.onepf.pushchat.model.response.RegistrationResponse; import org.onepf.pushchat.model.response.TopicsResponse; import org.onepf.pushchat.model.response.UnregistrationResponse; import org.onepf.pushchat.model.response.push.PushMessageResponse; import retrofit.Callback; import retrofit.http.Body;
/* * Copyright 2012-2015 One Platform Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onepf.pushchat.retrofit; /** * @author Roman Savin * @since 19.04.2015 */ public interface PushService { @POST("/register") void register(@Body @NonNull final RegistrationRequestBody body,
// Path: samples/pushchat/src/main/java/org/onepf/pushchat/model/request/RegistrationRequestBody.java // public final class RegistrationRequestBody extends RequestBody { // // @SerializedName("providerName") // @NonNull // public final String providerName; // // @SerializedName("registrationId") // @NonNull // public final String registrationId; // // public RegistrationRequestBody(@NonNull final String uuid, // @NonNull final String providerName, // @NonNull final String registrationId) { // super(uuid); // this.providerName = providerName; // this.registrationId = registrationId; // } // } // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/model/request/SubscribeOrUnsubscribeRequestBody.java // public final class SubscribeOrUnsubscribeRequestBody { // // @NonNull // public final String topic; // // @NonNull // public final String uuid; // // public SubscribeOrUnsubscribeRequestBody(@NonNull final String topic, @NonNull final String uuid) { // this.topic = topic; // this.uuid = uuid; // } // } // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/model/request/UnregistrationRequestBody.java // public final class UnregistrationRequestBody extends RequestBody { // // public UnregistrationRequestBody(@NonNull final String uuid) { // super(uuid); // } // } // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/model/request/push/PushMessageRequestBody.java // public final class PushMessageRequestBody { // // @SerializedName("uuids") // public final Set<String> uuids; // // @SerializedName("sender") // public final String sender; // // @SerializedName("message") // @NonNull // public final String message; // // public PushMessageRequestBody(@NonNull final Set<String> uuids, // @NonNull final String sender, // @NonNull final String message) { // this.uuids = uuids; // this.sender = sender; // this.message = message; // } // } // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/model/response/ExistResponse.java // public final class ExistResponse { // // @SerializedName("exist") // public final boolean exist; // // public ExistResponse(final boolean exist) { // this.exist = exist; // } // } // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/model/response/RegistrationResponse.java // public final class RegistrationResponse { // // @NonNull // public final String uuid; // // @NonNull // public final String providerName; // // @NonNull // public final String registrationId; // // public RegistrationResponse(@NonNull final String uuid, // @NonNull final String providerName, // @NonNull final String registrationId) { // this.uuid = uuid; // this.providerName = providerName; // this.registrationId = registrationId; // } // } // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/model/response/TopicsResponse.java // public final class TopicsResponse { // // @SerializedName("topics") // @Nullable // public final List<String> topics; // // public TopicsResponse(@Nullable final List<String> topics) { // this.topics = topics; // } // } // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/model/response/UnregistrationResponse.java // public final class UnregistrationResponse { // // @NonNull // public final String uuid; // // @Nullable // public final String providerName; // // @Nullable // public final String registrationId; // // public UnregistrationResponse(@NonNull final String uuid, // @Nullable final String providerName, // @Nullable final String registrationId) { // this.uuid = uuid; // this.providerName = providerName; // this.registrationId = registrationId; // } // } // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/model/response/push/PushMessageResponse.java // public final class PushMessageResponse { // // @Nullable // public final PushResult[] successed; // // @Nullable // public final FailedPushResult[] failed; // // @NonNull // public final String message; // // public PushMessageResponse(@Nullable final PushResult[] successed, // @Nullable final FailedPushResult[] failed, // @NonNull final String message) { // this.successed = successed; // this.failed = failed; // this.message = message; // } // } // Path: samples/pushchat/src/main/java/org/onepf/pushchat/retrofit/PushService.java import retrofit.http.GET; import retrofit.http.POST; import retrofit.http.Query; import android.support.annotation.NonNull; import org.onepf.pushchat.model.request.RegistrationRequestBody; import org.onepf.pushchat.model.request.SubscribeOrUnsubscribeRequestBody; import org.onepf.pushchat.model.request.UnregistrationRequestBody; import org.onepf.pushchat.model.request.push.PushMessageRequestBody; import org.onepf.pushchat.model.response.ExistResponse; import org.onepf.pushchat.model.response.RegistrationResponse; import org.onepf.pushchat.model.response.TopicsResponse; import org.onepf.pushchat.model.response.UnregistrationResponse; import org.onepf.pushchat.model.response.push.PushMessageResponse; import retrofit.Callback; import retrofit.http.Body; /* * Copyright 2012-2015 One Platform Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onepf.pushchat.retrofit; /** * @author Roman Savin * @since 19.04.2015 */ public interface PushService { @POST("/register") void register(@Body @NonNull final RegistrationRequestBody body,
@NonNull final Callback<RegistrationResponse> callback);
onepf/OPFPush
samples/pushchat/src/main/java/org/onepf/pushchat/retrofit/PushService.java
// Path: samples/pushchat/src/main/java/org/onepf/pushchat/model/request/RegistrationRequestBody.java // public final class RegistrationRequestBody extends RequestBody { // // @SerializedName("providerName") // @NonNull // public final String providerName; // // @SerializedName("registrationId") // @NonNull // public final String registrationId; // // public RegistrationRequestBody(@NonNull final String uuid, // @NonNull final String providerName, // @NonNull final String registrationId) { // super(uuid); // this.providerName = providerName; // this.registrationId = registrationId; // } // } // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/model/request/SubscribeOrUnsubscribeRequestBody.java // public final class SubscribeOrUnsubscribeRequestBody { // // @NonNull // public final String topic; // // @NonNull // public final String uuid; // // public SubscribeOrUnsubscribeRequestBody(@NonNull final String topic, @NonNull final String uuid) { // this.topic = topic; // this.uuid = uuid; // } // } // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/model/request/UnregistrationRequestBody.java // public final class UnregistrationRequestBody extends RequestBody { // // public UnregistrationRequestBody(@NonNull final String uuid) { // super(uuid); // } // } // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/model/request/push/PushMessageRequestBody.java // public final class PushMessageRequestBody { // // @SerializedName("uuids") // public final Set<String> uuids; // // @SerializedName("sender") // public final String sender; // // @SerializedName("message") // @NonNull // public final String message; // // public PushMessageRequestBody(@NonNull final Set<String> uuids, // @NonNull final String sender, // @NonNull final String message) { // this.uuids = uuids; // this.sender = sender; // this.message = message; // } // } // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/model/response/ExistResponse.java // public final class ExistResponse { // // @SerializedName("exist") // public final boolean exist; // // public ExistResponse(final boolean exist) { // this.exist = exist; // } // } // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/model/response/RegistrationResponse.java // public final class RegistrationResponse { // // @NonNull // public final String uuid; // // @NonNull // public final String providerName; // // @NonNull // public final String registrationId; // // public RegistrationResponse(@NonNull final String uuid, // @NonNull final String providerName, // @NonNull final String registrationId) { // this.uuid = uuid; // this.providerName = providerName; // this.registrationId = registrationId; // } // } // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/model/response/TopicsResponse.java // public final class TopicsResponse { // // @SerializedName("topics") // @Nullable // public final List<String> topics; // // public TopicsResponse(@Nullable final List<String> topics) { // this.topics = topics; // } // } // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/model/response/UnregistrationResponse.java // public final class UnregistrationResponse { // // @NonNull // public final String uuid; // // @Nullable // public final String providerName; // // @Nullable // public final String registrationId; // // public UnregistrationResponse(@NonNull final String uuid, // @Nullable final String providerName, // @Nullable final String registrationId) { // this.uuid = uuid; // this.providerName = providerName; // this.registrationId = registrationId; // } // } // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/model/response/push/PushMessageResponse.java // public final class PushMessageResponse { // // @Nullable // public final PushResult[] successed; // // @Nullable // public final FailedPushResult[] failed; // // @NonNull // public final String message; // // public PushMessageResponse(@Nullable final PushResult[] successed, // @Nullable final FailedPushResult[] failed, // @NonNull final String message) { // this.successed = successed; // this.failed = failed; // this.message = message; // } // }
import retrofit.http.GET; import retrofit.http.POST; import retrofit.http.Query; import android.support.annotation.NonNull; import org.onepf.pushchat.model.request.RegistrationRequestBody; import org.onepf.pushchat.model.request.SubscribeOrUnsubscribeRequestBody; import org.onepf.pushchat.model.request.UnregistrationRequestBody; import org.onepf.pushchat.model.request.push.PushMessageRequestBody; import org.onepf.pushchat.model.response.ExistResponse; import org.onepf.pushchat.model.response.RegistrationResponse; import org.onepf.pushchat.model.response.TopicsResponse; import org.onepf.pushchat.model.response.UnregistrationResponse; import org.onepf.pushchat.model.response.push.PushMessageResponse; import retrofit.Callback; import retrofit.http.Body;
/* * Copyright 2012-2015 One Platform Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onepf.pushchat.retrofit; /** * @author Roman Savin * @since 19.04.2015 */ public interface PushService { @POST("/register") void register(@Body @NonNull final RegistrationRequestBody body, @NonNull final Callback<RegistrationResponse> callback); @POST("/unregister")
// Path: samples/pushchat/src/main/java/org/onepf/pushchat/model/request/RegistrationRequestBody.java // public final class RegistrationRequestBody extends RequestBody { // // @SerializedName("providerName") // @NonNull // public final String providerName; // // @SerializedName("registrationId") // @NonNull // public final String registrationId; // // public RegistrationRequestBody(@NonNull final String uuid, // @NonNull final String providerName, // @NonNull final String registrationId) { // super(uuid); // this.providerName = providerName; // this.registrationId = registrationId; // } // } // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/model/request/SubscribeOrUnsubscribeRequestBody.java // public final class SubscribeOrUnsubscribeRequestBody { // // @NonNull // public final String topic; // // @NonNull // public final String uuid; // // public SubscribeOrUnsubscribeRequestBody(@NonNull final String topic, @NonNull final String uuid) { // this.topic = topic; // this.uuid = uuid; // } // } // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/model/request/UnregistrationRequestBody.java // public final class UnregistrationRequestBody extends RequestBody { // // public UnregistrationRequestBody(@NonNull final String uuid) { // super(uuid); // } // } // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/model/request/push/PushMessageRequestBody.java // public final class PushMessageRequestBody { // // @SerializedName("uuids") // public final Set<String> uuids; // // @SerializedName("sender") // public final String sender; // // @SerializedName("message") // @NonNull // public final String message; // // public PushMessageRequestBody(@NonNull final Set<String> uuids, // @NonNull final String sender, // @NonNull final String message) { // this.uuids = uuids; // this.sender = sender; // this.message = message; // } // } // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/model/response/ExistResponse.java // public final class ExistResponse { // // @SerializedName("exist") // public final boolean exist; // // public ExistResponse(final boolean exist) { // this.exist = exist; // } // } // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/model/response/RegistrationResponse.java // public final class RegistrationResponse { // // @NonNull // public final String uuid; // // @NonNull // public final String providerName; // // @NonNull // public final String registrationId; // // public RegistrationResponse(@NonNull final String uuid, // @NonNull final String providerName, // @NonNull final String registrationId) { // this.uuid = uuid; // this.providerName = providerName; // this.registrationId = registrationId; // } // } // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/model/response/TopicsResponse.java // public final class TopicsResponse { // // @SerializedName("topics") // @Nullable // public final List<String> topics; // // public TopicsResponse(@Nullable final List<String> topics) { // this.topics = topics; // } // } // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/model/response/UnregistrationResponse.java // public final class UnregistrationResponse { // // @NonNull // public final String uuid; // // @Nullable // public final String providerName; // // @Nullable // public final String registrationId; // // public UnregistrationResponse(@NonNull final String uuid, // @Nullable final String providerName, // @Nullable final String registrationId) { // this.uuid = uuid; // this.providerName = providerName; // this.registrationId = registrationId; // } // } // // Path: samples/pushchat/src/main/java/org/onepf/pushchat/model/response/push/PushMessageResponse.java // public final class PushMessageResponse { // // @Nullable // public final PushResult[] successed; // // @Nullable // public final FailedPushResult[] failed; // // @NonNull // public final String message; // // public PushMessageResponse(@Nullable final PushResult[] successed, // @Nullable final FailedPushResult[] failed, // @NonNull final String message) { // this.successed = successed; // this.failed = failed; // this.message = message; // } // } // Path: samples/pushchat/src/main/java/org/onepf/pushchat/retrofit/PushService.java import retrofit.http.GET; import retrofit.http.POST; import retrofit.http.Query; import android.support.annotation.NonNull; import org.onepf.pushchat.model.request.RegistrationRequestBody; import org.onepf.pushchat.model.request.SubscribeOrUnsubscribeRequestBody; import org.onepf.pushchat.model.request.UnregistrationRequestBody; import org.onepf.pushchat.model.request.push.PushMessageRequestBody; import org.onepf.pushchat.model.response.ExistResponse; import org.onepf.pushchat.model.response.RegistrationResponse; import org.onepf.pushchat.model.response.TopicsResponse; import org.onepf.pushchat.model.response.UnregistrationResponse; import org.onepf.pushchat.model.response.push.PushMessageResponse; import retrofit.Callback; import retrofit.http.Body; /* * Copyright 2012-2015 One Platform Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onepf.pushchat.retrofit; /** * @author Roman Savin * @since 19.04.2015 */ public interface PushService { @POST("/register") void register(@Body @NonNull final RegistrationRequestBody body, @NonNull final Callback<RegistrationResponse> callback); @POST("/unregister")
void unregister(@Body @NonNull final UnregistrationRequestBody body,
onepf/OPFPush
opfpush-providers/adm/src/main/java/org/onepf/opfpush/adm/ADMProviderStub.java
// Path: opfpush/src/main/java/org/onepf/opfpush/listener/CheckManifestHandler.java // public interface CheckManifestHandler { // // /** // * Called when some check manifest error occurred. // * // * @param reportMessage The information about error. // */ // void onCheckManifestError(@NonNull final String reportMessage); // } // // Path: opfpush/src/main/java/org/onepf/opfpush/model/AvailabilityResult.java // public final class AvailabilityResult { // // private boolean isAvailable; // // @Nullable // private Integer errorCode; // // public AvailabilityResult(final boolean isAvailable) { // this(isAvailable, null); // } // // public AvailabilityResult(@NonNull final Integer errorCode) { // this(false, errorCode); // } // // public AvailabilityResult(final boolean isAvailable, @Nullable final Integer errorCode) { // this.isAvailable = isAvailable; // this.errorCode = errorCode; // } // // /** // * Returns {@code true} if a provider is available, false otherwise. // * // * @return {@code true} if a provider is available, false otherwise. // */ // public boolean isAvailable() { // return isAvailable; // } // // /** // * Returns a specific provider error code. // * // * @return The availability error code, or {@code null} if a provider hasn't returned a error code. // */ // @Nullable // public Integer getErrorCode() { // return errorCode; // } // } // // Path: opfpush/src/main/java/org/onepf/opfpush/notification/NotificationMaker.java // public interface NotificationMaker { // // /** // * Returns true if a notification must be shown for the bundle. False otherwise. // * // * @param bundle The bundle received from a push provider. // * @return Returns true if a notification should be shown for the bundle. False otherwise. // */ // boolean needShowNotification(@NonNull final Bundle bundle); // // /** // * Shows notification using bundle data. // * // * @param context The Context instance. // * @param bundle Received data. // */ // void showNotification(@NonNull final Context context, @NonNull final Bundle bundle); // } // // Path: opfpush/src/main/java/org/onepf/opfpush/pushprovider/PushProvider.java // public interface PushProvider { // /** // * Initiates the registration of the provider. Must be async. // * <p/> // * Intended for the internal use, should never be called directly. // * To start the registration call {@link org.onepf.opfpush.OPFPushHelper#register()}. // */ // void register(); // // /** // * Initiates the unregistering of the provider. Must be async. // * <p/> // * Intended for internal use, should never be called directly. // * To start registration call {@link org.onepf.opfpush.OPFPushHelper#unregister()}. // */ // void unregister(); // // /** // * Checks whether the provider is available. // * // * @return The instance of {@link org.onepf.opfpush.model.AvailabilityResult} // * that contains result of availability check. // */ // @NonNull // AvailabilityResult getAvailabilityResult(); // // /** // * Checks whether the application was successfully registered on the service. // * // * @return {@code true} if the application was successfully registered on the service, otherwise false. // */ // boolean isRegistered(); // // /** // * Returns the registration ID or null if provider isn't registered. // * // * @return The registration ID or null if provider isn't registered. // */ // @Nullable // String getRegistrationId(); // // /** // * Returns the name of the provider. Must be unique for all providers. // * // * @return The name of the provider. // */ // @NonNull // String getName(); // // /** // * Returns the package of the application that contains API of the provider. // * Usually, this is a store application. // * // * @return The package of the application that contains API of the provider. // */ // @Nullable // String getHostAppPackage(); // // /** // * Returns the {@link NotificationMaker} object associated with provider. // * // * @return The {@link NotificationMaker} instance. // */ // @NonNull // NotificationMaker getNotificationMaker(); // // /** // * Verify that application manifest contains all needed permissions. // * // * @param checkManifestHandler If not null an exception isn't thrown. // * @throws java.lang.IllegalStateException If not all required permissions and components have been // * described in the AndroidManifest.xml file. // */ // void checkManifest(@Nullable CheckManifestHandler checkManifestHandler); // // /** // * Callback method, that called when the application state change, like update to new version, // * or system state changed, like update firmware to a newer version. // * <p/> // * If this method is called, your registration becomes invalid // * and you have to reset all saved registration data. // */ // void onRegistrationInvalid(); // // /** // * Callback method for notify that the provider became unavailable. // * In this method you have to reset all saved registration data. // */ // void onUnavailable(); // } // // Path: opfpush-providers/adm/src/main/java/org/onepf/opfpush/adm/ADMConstants.java // public static final String PROVIDER_NAME = "Amazon Device Messaging";
import android.content.Context; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import org.onepf.opfpush.listener.CheckManifestHandler; import org.onepf.opfpush.model.AvailabilityResult; import org.onepf.opfpush.notification.NotificationMaker; import org.onepf.opfpush.pushprovider.PushProvider; import org.onepf.opfutils.OPFLog; import static org.onepf.opfpush.adm.ADMConstants.PROVIDER_NAME;
@Override public boolean isRegistered() { OPFLog.logMethod(); return false; } @Nullable @Override public String getRegistrationId() { OPFLog.logMethod(); return null; } @NonNull @Override public String getName() { OPFLog.logMethod(); return PROVIDER_NAME; } @Nullable @Override public String getHostAppPackage() { OPFLog.logMethod(); return null; } @NonNull @Override
// Path: opfpush/src/main/java/org/onepf/opfpush/listener/CheckManifestHandler.java // public interface CheckManifestHandler { // // /** // * Called when some check manifest error occurred. // * // * @param reportMessage The information about error. // */ // void onCheckManifestError(@NonNull final String reportMessage); // } // // Path: opfpush/src/main/java/org/onepf/opfpush/model/AvailabilityResult.java // public final class AvailabilityResult { // // private boolean isAvailable; // // @Nullable // private Integer errorCode; // // public AvailabilityResult(final boolean isAvailable) { // this(isAvailable, null); // } // // public AvailabilityResult(@NonNull final Integer errorCode) { // this(false, errorCode); // } // // public AvailabilityResult(final boolean isAvailable, @Nullable final Integer errorCode) { // this.isAvailable = isAvailable; // this.errorCode = errorCode; // } // // /** // * Returns {@code true} if a provider is available, false otherwise. // * // * @return {@code true} if a provider is available, false otherwise. // */ // public boolean isAvailable() { // return isAvailable; // } // // /** // * Returns a specific provider error code. // * // * @return The availability error code, or {@code null} if a provider hasn't returned a error code. // */ // @Nullable // public Integer getErrorCode() { // return errorCode; // } // } // // Path: opfpush/src/main/java/org/onepf/opfpush/notification/NotificationMaker.java // public interface NotificationMaker { // // /** // * Returns true if a notification must be shown for the bundle. False otherwise. // * // * @param bundle The bundle received from a push provider. // * @return Returns true if a notification should be shown for the bundle. False otherwise. // */ // boolean needShowNotification(@NonNull final Bundle bundle); // // /** // * Shows notification using bundle data. // * // * @param context The Context instance. // * @param bundle Received data. // */ // void showNotification(@NonNull final Context context, @NonNull final Bundle bundle); // } // // Path: opfpush/src/main/java/org/onepf/opfpush/pushprovider/PushProvider.java // public interface PushProvider { // /** // * Initiates the registration of the provider. Must be async. // * <p/> // * Intended for the internal use, should never be called directly. // * To start the registration call {@link org.onepf.opfpush.OPFPushHelper#register()}. // */ // void register(); // // /** // * Initiates the unregistering of the provider. Must be async. // * <p/> // * Intended for internal use, should never be called directly. // * To start registration call {@link org.onepf.opfpush.OPFPushHelper#unregister()}. // */ // void unregister(); // // /** // * Checks whether the provider is available. // * // * @return The instance of {@link org.onepf.opfpush.model.AvailabilityResult} // * that contains result of availability check. // */ // @NonNull // AvailabilityResult getAvailabilityResult(); // // /** // * Checks whether the application was successfully registered on the service. // * // * @return {@code true} if the application was successfully registered on the service, otherwise false. // */ // boolean isRegistered(); // // /** // * Returns the registration ID or null if provider isn't registered. // * // * @return The registration ID or null if provider isn't registered. // */ // @Nullable // String getRegistrationId(); // // /** // * Returns the name of the provider. Must be unique for all providers. // * // * @return The name of the provider. // */ // @NonNull // String getName(); // // /** // * Returns the package of the application that contains API of the provider. // * Usually, this is a store application. // * // * @return The package of the application that contains API of the provider. // */ // @Nullable // String getHostAppPackage(); // // /** // * Returns the {@link NotificationMaker} object associated with provider. // * // * @return The {@link NotificationMaker} instance. // */ // @NonNull // NotificationMaker getNotificationMaker(); // // /** // * Verify that application manifest contains all needed permissions. // * // * @param checkManifestHandler If not null an exception isn't thrown. // * @throws java.lang.IllegalStateException If not all required permissions and components have been // * described in the AndroidManifest.xml file. // */ // void checkManifest(@Nullable CheckManifestHandler checkManifestHandler); // // /** // * Callback method, that called when the application state change, like update to new version, // * or system state changed, like update firmware to a newer version. // * <p/> // * If this method is called, your registration becomes invalid // * and you have to reset all saved registration data. // */ // void onRegistrationInvalid(); // // /** // * Callback method for notify that the provider became unavailable. // * In this method you have to reset all saved registration data. // */ // void onUnavailable(); // } // // Path: opfpush-providers/adm/src/main/java/org/onepf/opfpush/adm/ADMConstants.java // public static final String PROVIDER_NAME = "Amazon Device Messaging"; // Path: opfpush-providers/adm/src/main/java/org/onepf/opfpush/adm/ADMProviderStub.java import android.content.Context; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import org.onepf.opfpush.listener.CheckManifestHandler; import org.onepf.opfpush.model.AvailabilityResult; import org.onepf.opfpush.notification.NotificationMaker; import org.onepf.opfpush.pushprovider.PushProvider; import org.onepf.opfutils.OPFLog; import static org.onepf.opfpush.adm.ADMConstants.PROVIDER_NAME; @Override public boolean isRegistered() { OPFLog.logMethod(); return false; } @Nullable @Override public String getRegistrationId() { OPFLog.logMethod(); return null; } @NonNull @Override public String getName() { OPFLog.logMethod(); return PROVIDER_NAME; } @Nullable @Override public String getHostAppPackage() { OPFLog.logMethod(); return null; } @NonNull @Override
public NotificationMaker getNotificationMaker() {
onepf/OPFPush
opfpush-providers/gcm/src/main/java/org/onepf/opfpush/gcm/GCMInstanceIDListenerService.java
// Path: opfpush/src/main/java/org/onepf/opfpush/OPFPush.java // public final class OPFPush { // // private static volatile OPFPushHelper helper; // // private OPFPush() { // throw new UnsupportedOperationException(); // } // // /** // * Returns the {@link org.onepf.opfpush.OPFPushHelper} instance. // * // * @return The {@link org.onepf.opfpush.OPFPushHelper} instance. // * @throws org.onepf.opfutils.exception.InitException If {@code OPFPush} wasn't initialized. // */ // @NonNull // public static OPFPushHelper getHelper() { // OPFLog.logMethod(); // if (helper == null) { // throw new InitException(false); // } // return helper; // } // // /** // * Initializes the OPFPush library and creates the {@link org.onepf.opfpush.OPFPushHelper} singleton instance. // * // * @param context The {@link android.content.Context} instance. // * @param configuration The {@link org.onepf.opfpush.configuration.Configuration} instance. // * @throws org.onepf.opfutils.exception.WrongThreadException If this method is not called from the main thread. // * @throws org.onepf.opfutils.exception.InitException If the {@code OPFPush} has already been initialized. // */ // public static void init(@NonNull final Context context, // @NonNull final Configuration configuration) { // OPFLog.logMethod(context, configuration); // OPFChecks.checkThread(true); // // if (helper != null) { // throw new InitException(true); // } // // if (OPFUtils.isMainProcess(context)) { // OPFLog.i("Init in main process"); // final OPFPushHelper newHelper = new OPFPushHelperImpl(context); // newHelper.init(configuration); // helper = newHelper; // } else { // OPFLog.i("Init in not main process"); // helper = new OPFPushHelperStub(); // } // } // }
import com.google.android.gms.iid.InstanceIDListenerService; import org.onepf.opfpush.OPFPush; import org.onepf.opfutils.OPFLog;
/* * Copyright 2012-2015 One Platform Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onepf.opfpush.gcm; /** * It performs reregistration of the GCMProvider in the implementation of the {@code onTokenRefresh()} method. * * @author Roman Savin * @since 16.06.2015 */ public class GCMInstanceIDListenerService extends InstanceIDListenerService { @Override public void onTokenRefresh() { OPFLog.logMethod();
// Path: opfpush/src/main/java/org/onepf/opfpush/OPFPush.java // public final class OPFPush { // // private static volatile OPFPushHelper helper; // // private OPFPush() { // throw new UnsupportedOperationException(); // } // // /** // * Returns the {@link org.onepf.opfpush.OPFPushHelper} instance. // * // * @return The {@link org.onepf.opfpush.OPFPushHelper} instance. // * @throws org.onepf.opfutils.exception.InitException If {@code OPFPush} wasn't initialized. // */ // @NonNull // public static OPFPushHelper getHelper() { // OPFLog.logMethod(); // if (helper == null) { // throw new InitException(false); // } // return helper; // } // // /** // * Initializes the OPFPush library and creates the {@link org.onepf.opfpush.OPFPushHelper} singleton instance. // * // * @param context The {@link android.content.Context} instance. // * @param configuration The {@link org.onepf.opfpush.configuration.Configuration} instance. // * @throws org.onepf.opfutils.exception.WrongThreadException If this method is not called from the main thread. // * @throws org.onepf.opfutils.exception.InitException If the {@code OPFPush} has already been initialized. // */ // public static void init(@NonNull final Context context, // @NonNull final Configuration configuration) { // OPFLog.logMethod(context, configuration); // OPFChecks.checkThread(true); // // if (helper != null) { // throw new InitException(true); // } // // if (OPFUtils.isMainProcess(context)) { // OPFLog.i("Init in main process"); // final OPFPushHelper newHelper = new OPFPushHelperImpl(context); // newHelper.init(configuration); // helper = newHelper; // } else { // OPFLog.i("Init in not main process"); // helper = new OPFPushHelperStub(); // } // } // } // Path: opfpush-providers/gcm/src/main/java/org/onepf/opfpush/gcm/GCMInstanceIDListenerService.java import com.google.android.gms.iid.InstanceIDListenerService; import org.onepf.opfpush.OPFPush; import org.onepf.opfutils.OPFLog; /* * Copyright 2012-2015 One Platform Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onepf.opfpush.gcm; /** * It performs reregistration of the GCMProvider in the implementation of the {@code onTokenRefresh()} method. * * @author Roman Savin * @since 16.06.2015 */ public class GCMInstanceIDListenerService extends InstanceIDListenerService { @Override public void onTokenRefresh() { OPFLog.logMethod();
OPFPush.getHelper().onNeedRetryRegistration();
demoiselle/framework3
framework/src/main/java/org/demoiselle/jsf/internal/producer/ParameterProducer.java
// Path: framework/src/main/java/org/demoiselle/jsf/util/Parameter.java // public interface Parameter<T extends Serializable> extends Serializable { // // void setValue(T value); // // String getKey(); // // T getValue(); // // }
import org.demoiselle.annotation.Name; import org.demoiselle.jsf.internal.implementation.ParameterImpl; import org.demoiselle.jsf.util.Parameter; import javax.enterprise.context.Dependent; import javax.enterprise.inject.Default; import javax.enterprise.inject.Produces; import javax.enterprise.inject.spi.InjectionPoint; import javax.inject.Inject; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import java.io.Serializable;
/* * Demoiselle Framework * Copyright (C) 2010 SERPRO * ---------------------------------------------------------------------------- * This file is part of Demoiselle Framework. * * Demoiselle Framework is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License version 3 * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License version 3 * along with this program; if not, see <http://www.gnu.org/licenses/> * or write to the Free Software Foundation, Inc., 51 Franklin Street, * Fifth Floor, Boston, MA 02110-1301, USA. * ---------------------------------------------------------------------------- * Este arquivo é parte do Framework Demoiselle. * * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação * do Software Livre (FSF). * * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português * para maiores detalhes. * * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título * "LICENCA.txt", junto com esse programa. Se não, acesse <http://www.gnu.org/licenses/> * ou escreva para a Fundação do Software Livre (FSF) Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. */ /* * Demoiselle Framework Copyright (c) 2010 Serpro and other contributors as indicated by the @author tag. See the * copyright.txt in the distribution for a full listing of contributors. Demoiselle Framework is an open source Java EE * library designed to accelerate the development of transactional database Web applications. Demoiselle Framework is * released under the terms of the LGPL license 3 http://www.gnu.org/licenses/lgpl.html LGPL License 3 This file is part * of Demoiselle Framework. Demoiselle Framework is free software: you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License 3 as published by the Free Software Foundation. Demoiselle Framework * is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You * should have received a copy of the GNU Lesser General Public License along with Demoiselle Framework. If not, see * <http://www.gnu.org/licenses/>. */ package org.demoiselle.jsf.internal.producer; @Dependent public class ParameterProducer implements Serializable { private static final long serialVersionUID = 1L; @Default @Produces
// Path: framework/src/main/java/org/demoiselle/jsf/util/Parameter.java // public interface Parameter<T extends Serializable> extends Serializable { // // void setValue(T value); // // String getKey(); // // T getValue(); // // } // Path: framework/src/main/java/org/demoiselle/jsf/internal/producer/ParameterProducer.java import org.demoiselle.annotation.Name; import org.demoiselle.jsf.internal.implementation.ParameterImpl; import org.demoiselle.jsf.util.Parameter; import javax.enterprise.context.Dependent; import javax.enterprise.inject.Default; import javax.enterprise.inject.Produces; import javax.enterprise.inject.spi.InjectionPoint; import javax.inject.Inject; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import java.io.Serializable; /* * Demoiselle Framework * Copyright (C) 2010 SERPRO * ---------------------------------------------------------------------------- * This file is part of Demoiselle Framework. * * Demoiselle Framework is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License version 3 * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License version 3 * along with this program; if not, see <http://www.gnu.org/licenses/> * or write to the Free Software Foundation, Inc., 51 Franklin Street, * Fifth Floor, Boston, MA 02110-1301, USA. * ---------------------------------------------------------------------------- * Este arquivo é parte do Framework Demoiselle. * * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação * do Software Livre (FSF). * * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português * para maiores detalhes. * * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título * "LICENCA.txt", junto com esse programa. Se não, acesse <http://www.gnu.org/licenses/> * ou escreva para a Fundação do Software Livre (FSF) Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. */ /* * Demoiselle Framework Copyright (c) 2010 Serpro and other contributors as indicated by the @author tag. See the * copyright.txt in the distribution for a full listing of contributors. Demoiselle Framework is an open source Java EE * library designed to accelerate the development of transactional database Web applications. Demoiselle Framework is * released under the terms of the LGPL license 3 http://www.gnu.org/licenses/lgpl.html LGPL License 3 This file is part * of Demoiselle Framework. Demoiselle Framework is free software: you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License 3 as published by the Free Software Foundation. Demoiselle Framework * is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You * should have received a copy of the GNU Lesser General Public License along with Demoiselle Framework. If not, see * <http://www.gnu.org/licenses/>. */ package org.demoiselle.jsf.internal.producer; @Dependent public class ParameterProducer implements Serializable { private static final long serialVersionUID = 1L; @Default @Produces
public <T extends Serializable> Parameter<T> createDefault(final InjectionPoint ip) {
demoiselle/framework3
framework/src/main/java/org/demoiselle/rest/internal/implementation/ConstraintViolationExceptionMapper.java
// Path: framework/src/main/java/org/demoiselle/annotation/literal/NameQualifier.java // @SuppressWarnings("all") // public class NameQualifier extends AnnotationLiteral<Name> implements Name { // // private static final long serialVersionUID = 1L; // // private final String value; // // /** // * Constructor with string value of name literal. // * // * @param value value of name literal. // */ // public NameQualifier(String value) { // this.value = value; // } // // @Override // public String value() { // return this.value; // } // }
import org.demoiselle.annotation.literal.NameQualifier; import org.demoiselle.rest.UnprocessableEntityException; import org.demoiselle.util.ResourceBundle; import javax.enterprise.inject.spi.CDI; import javax.validation.ConstraintViolation; import javax.validation.ConstraintViolationException; import javax.ws.rs.core.Response; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Provider; import java.util.Iterator; import java.util.logging.Logger;
/* * Demoiselle Framework * Copyright (C) 2010 SERPRO * ---------------------------------------------------------------------------- * This file is part of Demoiselle Framework. * * Demoiselle Framework is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License version 3 * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License version 3 * along with this program; if not, see <http://www.gnu.org/licenses/> * or write to the Free Software Foundation, Inc., 51 Franklin Street, * Fifth Floor, Boston, MA 02110-1301, USA. * ---------------------------------------------------------------------------- * Este arquivo é parte do Framework Demoiselle. * * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação * do Software Livre (FSF). * * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português * para maiores detalhes. * * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título * "LICENCA.txt", junto com esse programa. Se não, acesse <http://www.gnu.org/licenses/> * ou escreva para a Fundação do Software Livre (FSF) Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. */ package org.demoiselle.rest.internal.implementation; /** * @author SERPRO */ @Provider public class ConstraintViolationExceptionMapper implements ExceptionMapper<ConstraintViolationException> { private transient ResourceBundle bundle; private transient Logger logger; @Override public Response toResponse(ConstraintViolationException exception) { UnprocessableEntityException failed = new UnprocessableEntityException(); int status = new UnprocessableEntityException().getStatusCode(); for (Iterator<ConstraintViolation<?>> iter = exception.getConstraintViolations().iterator(); iter.hasNext();) { ConstraintViolation<?> violation = iter.next(); String property = getPropertyViolationName(violation); failed.addViolation(property, violation.getMessage()); } getLogger().fine(getBundle().getString("mapping-violations", status, failed.getViolations().toString())); Object entity = failed.getViolations(); String mediaType = failed.getMediaType(); return Response.status(status).entity(entity).type(mediaType).build(); } /** *Método que separa as partes da string que representa a propriedade na qual a violação * ocorreu, e devolve apenas a última parte, que é corresponde apenas ao nome do atributo. * * @param violation a ConstraintViolation ocorrida. * * @return o nome da propriedade que causou a violação. * */ private String getPropertyViolationName(ConstraintViolation violation){ /*Na implementação desse método estamos considerando que o property path (getPropertyPath().toString()) * retorna sempre uma string no formato nomemetodo.posicaoargumento.nomeatributo, do qual iremos extrair * a última parte. * */ //TODO: Verificar se a especificação determina esse formato, ou se essa é a implementação do Hibernate. String[] propertyParts = violation.getPropertyPath().toString().split("\\."); return propertyParts[2]; } private ResourceBundle getBundle() { if (bundle == null) {
// Path: framework/src/main/java/org/demoiselle/annotation/literal/NameQualifier.java // @SuppressWarnings("all") // public class NameQualifier extends AnnotationLiteral<Name> implements Name { // // private static final long serialVersionUID = 1L; // // private final String value; // // /** // * Constructor with string value of name literal. // * // * @param value value of name literal. // */ // public NameQualifier(String value) { // this.value = value; // } // // @Override // public String value() { // return this.value; // } // } // Path: framework/src/main/java/org/demoiselle/rest/internal/implementation/ConstraintViolationExceptionMapper.java import org.demoiselle.annotation.literal.NameQualifier; import org.demoiselle.rest.UnprocessableEntityException; import org.demoiselle.util.ResourceBundle; import javax.enterprise.inject.spi.CDI; import javax.validation.ConstraintViolation; import javax.validation.ConstraintViolationException; import javax.ws.rs.core.Response; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Provider; import java.util.Iterator; import java.util.logging.Logger; /* * Demoiselle Framework * Copyright (C) 2010 SERPRO * ---------------------------------------------------------------------------- * This file is part of Demoiselle Framework. * * Demoiselle Framework is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License version 3 * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License version 3 * along with this program; if not, see <http://www.gnu.org/licenses/> * or write to the Free Software Foundation, Inc., 51 Franklin Street, * Fifth Floor, Boston, MA 02110-1301, USA. * ---------------------------------------------------------------------------- * Este arquivo é parte do Framework Demoiselle. * * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação * do Software Livre (FSF). * * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português * para maiores detalhes. * * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título * "LICENCA.txt", junto com esse programa. Se não, acesse <http://www.gnu.org/licenses/> * ou escreva para a Fundação do Software Livre (FSF) Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. */ package org.demoiselle.rest.internal.implementation; /** * @author SERPRO */ @Provider public class ConstraintViolationExceptionMapper implements ExceptionMapper<ConstraintViolationException> { private transient ResourceBundle bundle; private transient Logger logger; @Override public Response toResponse(ConstraintViolationException exception) { UnprocessableEntityException failed = new UnprocessableEntityException(); int status = new UnprocessableEntityException().getStatusCode(); for (Iterator<ConstraintViolation<?>> iter = exception.getConstraintViolations().iterator(); iter.hasNext();) { ConstraintViolation<?> violation = iter.next(); String property = getPropertyViolationName(violation); failed.addViolation(property, violation.getMessage()); } getLogger().fine(getBundle().getString("mapping-violations", status, failed.getViolations().toString())); Object entity = failed.getViolations(); String mediaType = failed.getMediaType(); return Response.status(status).entity(entity).type(mediaType).build(); } /** *Método que separa as partes da string que representa a propriedade na qual a violação * ocorreu, e devolve apenas a última parte, que é corresponde apenas ao nome do atributo. * * @param violation a ConstraintViolation ocorrida. * * @return o nome da propriedade que causou a violação. * */ private String getPropertyViolationName(ConstraintViolation violation){ /*Na implementação desse método estamos considerando que o property path (getPropertyPath().toString()) * retorna sempre uma string no formato nomemetodo.posicaoargumento.nomeatributo, do qual iremos extrair * a última parte. * */ //TODO: Verificar se a especificação determina esse formato, ou se essa é a implementação do Hibernate. String[] propertyParts = violation.getPropertyPath().toString().split("\\."); return propertyParts[2]; } private ResourceBundle getBundle() { if (bundle == null) {
bundle = CDI.current().select(ResourceBundle.class, new NameQualifier("demoiselle-rest-bundle")).get();
demoiselle/framework3
bookmark-rest/src/main/java/br/gov/serpro/demoiselle/bookmark/security/BookmarkAuthenticator.java
// Path: framework/src/main/java/org/demoiselle/security/InvalidCredentialsException.java // public class InvalidCredentialsException extends AuthenticationException { // // private static final long serialVersionUID = 1L; // // public InvalidCredentialsException() { // super(CDI.current().select(ResourceBundle.class, new NameQualifier("demoiselle-core-bundle")).get().getString("invalid-credentials")); // } // // /** // * <p> // * Constructs an <code>InvalidCredentialsException</code> with a message. // * </p> // * // * @param message exception message. // */ // public InvalidCredentialsException(String message) { // super(message); // } // // /** // * <p> // * Constructor with message and cause. // * </p> // * // * @param message exception message. // * @param cause exception cause. // */ // public InvalidCredentialsException(String message, Throwable cause) { // super(message, cause); // } // }
import org.demoiselle.annotation.Priority; import org.demoiselle.security.Authenticator; import org.demoiselle.security.InvalidCredentialsException; import org.demoiselle.servlet.security.Credentials; import javax.enterprise.context.SessionScoped; import javax.enterprise.inject.spi.CDI; import java.security.Principal;
package br.gov.serpro.demoiselle.bookmark.security; /** * @author SERPRO */ @SessionScoped @Priority(Priority.L3_PRIORITY) public class BookmarkAuthenticator implements Authenticator { private static final long serialVersionUID = -118515447020255993L; private Principal principal; /** * Sample authenticator that authenticates any user with the password "secret". * @throws Exception If the authentication process fails */ @Override public void authenticate() throws Exception { Credentials credentials = CDI.current().select(Credentials.class).get(); if(credentials.getPassword().equals("secret")){ this.principal = credentials::getUsername; } else {
// Path: framework/src/main/java/org/demoiselle/security/InvalidCredentialsException.java // public class InvalidCredentialsException extends AuthenticationException { // // private static final long serialVersionUID = 1L; // // public InvalidCredentialsException() { // super(CDI.current().select(ResourceBundle.class, new NameQualifier("demoiselle-core-bundle")).get().getString("invalid-credentials")); // } // // /** // * <p> // * Constructs an <code>InvalidCredentialsException</code> with a message. // * </p> // * // * @param message exception message. // */ // public InvalidCredentialsException(String message) { // super(message); // } // // /** // * <p> // * Constructor with message and cause. // * </p> // * // * @param message exception message. // * @param cause exception cause. // */ // public InvalidCredentialsException(String message, Throwable cause) { // super(message, cause); // } // } // Path: bookmark-rest/src/main/java/br/gov/serpro/demoiselle/bookmark/security/BookmarkAuthenticator.java import org.demoiselle.annotation.Priority; import org.demoiselle.security.Authenticator; import org.demoiselle.security.InvalidCredentialsException; import org.demoiselle.servlet.security.Credentials; import javax.enterprise.context.SessionScoped; import javax.enterprise.inject.spi.CDI; import java.security.Principal; package br.gov.serpro.demoiselle.bookmark.security; /** * @author SERPRO */ @SessionScoped @Priority(Priority.L3_PRIORITY) public class BookmarkAuthenticator implements Authenticator { private static final long serialVersionUID = -118515447020255993L; private Principal principal; /** * Sample authenticator that authenticates any user with the password "secret". * @throws Exception If the authentication process fails */ @Override public void authenticate() throws Exception { Credentials credentials = CDI.current().select(Credentials.class).get(); if(credentials.getPassword().equals("secret")){ this.principal = credentials::getUsername; } else {
throw new InvalidCredentialsException();
demoiselle/framework3
framework/src/main/java/org/demoiselle/internal/bootstrap/ConfigurationBootstrap.java
// Path: framework/src/main/java/org/demoiselle/configuration/ConfigurationValueExtractor.java // @SuppressWarnings("unused") // public interface ConfigurationValueExtractor { // // /** // * Method that must appropriately extract the value from a property file and set this value to a // * field in a configuration class. // * // * @param prefix // * optional parte of property name that must be concatenated with <b>key</b> to form the whole // * property name. // * @param key // * key of the property. // * @param field // * configuration field to be setted. // * @param configuration // * a configuration object. // * @return current value of this property // * @throws Exception if the value can't be extracted from the property file // */ // Object getValue(String prefix, String key, Field field, Configuration configuration) throws Exception; // // /** // * Checks if the extractor class is appropriate to extract values to the type of deffined by parameter // * <b>field</b>. // * // * @param field // * field to be checked. // * @return <code>true</code> if this extractor can convert this field into the extractor's final type // */ // boolean isSupported(Field field); // } // // Path: framework/src/main/java/org/demoiselle/internal/producer/LoggerProducer.java // @Dependent // public class LoggerProducer implements Serializable { // // private static final long serialVersionUID = 1L; // // /* // * Produces a default {@link Logger} instance. If it's possible // * to infer the injection point's parent class then this class'es // * name will be used to categorize the logger, if not then // * the logger won't be categorized. // * // */ // @Default // @Produces // public Logger create(final InjectionPoint ip) { // String name; // // if (ip != null && ip.getMember() != null) { // name = ip.getMember().getDeclaringClass().getName(); // } else { // name = "not.categorized"; // } // // return create(name); // } // // /* // * Produces a {@link Logger} instance categorized by the value // * defined by the {@link Name} literal. // * // */ // @Name // @Produces // public Logger createNamed(final InjectionPoint ip) { // Name nameAnnotation = CDIUtils.getQualifier(Name.class, ip); // String name = nameAnnotation.value(); // return create(name); // } // // public static Logger create(String name) { // return new LoggerProxy(name); // } // }
import java.util.logging.Logger; import org.demoiselle.configuration.ConfigurationValueExtractor; import org.demoiselle.internal.producer.LoggerProducer;
/* * Demoiselle Framework * Copyright (C) 2010 SERPRO * ---------------------------------------------------------------------------- * This file is part of Demoiselle Framework. * * Demoiselle Framework is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License version 3 * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License version 3 * along with this program; if not, see <http://www.gnu.org/licenses/> * or write to the Free Software Foundation, Inc., 51 Franklin Street, * Fifth Floor, Boston, MA 02110-1301, USA. * ---------------------------------------------------------------------------- * Este arquivo é parte do Framework Demoiselle. * * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação * do Software Livre (FSF). * * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português * para maiores detalhes. * * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título * "LICENCA.txt", junto com esse programa. Se não, acesse <http://www.gnu.org/licenses/> * ou escreva para a Fundação do Software Livre (FSF) Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. */ package org.demoiselle.internal.bootstrap; public class ConfigurationBootstrap extends AbstractStrategyBootstrap<ConfigurationValueExtractor> { private Logger logger; @Override protected Logger getLogger() { if (logger == null) {
// Path: framework/src/main/java/org/demoiselle/configuration/ConfigurationValueExtractor.java // @SuppressWarnings("unused") // public interface ConfigurationValueExtractor { // // /** // * Method that must appropriately extract the value from a property file and set this value to a // * field in a configuration class. // * // * @param prefix // * optional parte of property name that must be concatenated with <b>key</b> to form the whole // * property name. // * @param key // * key of the property. // * @param field // * configuration field to be setted. // * @param configuration // * a configuration object. // * @return current value of this property // * @throws Exception if the value can't be extracted from the property file // */ // Object getValue(String prefix, String key, Field field, Configuration configuration) throws Exception; // // /** // * Checks if the extractor class is appropriate to extract values to the type of deffined by parameter // * <b>field</b>. // * // * @param field // * field to be checked. // * @return <code>true</code> if this extractor can convert this field into the extractor's final type // */ // boolean isSupported(Field field); // } // // Path: framework/src/main/java/org/demoiselle/internal/producer/LoggerProducer.java // @Dependent // public class LoggerProducer implements Serializable { // // private static final long serialVersionUID = 1L; // // /* // * Produces a default {@link Logger} instance. If it's possible // * to infer the injection point's parent class then this class'es // * name will be used to categorize the logger, if not then // * the logger won't be categorized. // * // */ // @Default // @Produces // public Logger create(final InjectionPoint ip) { // String name; // // if (ip != null && ip.getMember() != null) { // name = ip.getMember().getDeclaringClass().getName(); // } else { // name = "not.categorized"; // } // // return create(name); // } // // /* // * Produces a {@link Logger} instance categorized by the value // * defined by the {@link Name} literal. // * // */ // @Name // @Produces // public Logger createNamed(final InjectionPoint ip) { // Name nameAnnotation = CDIUtils.getQualifier(Name.class, ip); // String name = nameAnnotation.value(); // return create(name); // } // // public static Logger create(String name) { // return new LoggerProxy(name); // } // } // Path: framework/src/main/java/org/demoiselle/internal/bootstrap/ConfigurationBootstrap.java import java.util.logging.Logger; import org.demoiselle.configuration.ConfigurationValueExtractor; import org.demoiselle.internal.producer.LoggerProducer; /* * Demoiselle Framework * Copyright (C) 2010 SERPRO * ---------------------------------------------------------------------------- * This file is part of Demoiselle Framework. * * Demoiselle Framework is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License version 3 * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License version 3 * along with this program; if not, see <http://www.gnu.org/licenses/> * or write to the Free Software Foundation, Inc., 51 Franklin Street, * Fifth Floor, Boston, MA 02110-1301, USA. * ---------------------------------------------------------------------------- * Este arquivo é parte do Framework Demoiselle. * * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação * do Software Livre (FSF). * * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português * para maiores detalhes. * * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título * "LICENCA.txt", junto com esse programa. Se não, acesse <http://www.gnu.org/licenses/> * ou escreva para a Fundação do Software Livre (FSF) Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. */ package org.demoiselle.internal.bootstrap; public class ConfigurationBootstrap extends AbstractStrategyBootstrap<ConfigurationValueExtractor> { private Logger logger; @Override protected Logger getLogger() { if (logger == null) {
logger = LoggerProducer.create("br.gov.frameworkdemoiselle.configuration");
demoiselle/framework3
framework/src/main/java/org/demoiselle/security/InvalidCredentialsException.java
// Path: framework/src/main/java/org/demoiselle/annotation/literal/NameQualifier.java // @SuppressWarnings("all") // public class NameQualifier extends AnnotationLiteral<Name> implements Name { // // private static final long serialVersionUID = 1L; // // private final String value; // // /** // * Constructor with string value of name literal. // * // * @param value value of name literal. // */ // public NameQualifier(String value) { // this.value = value; // } // // @Override // public String value() { // return this.value; // } // }
import org.demoiselle.util.ResourceBundle; import javax.enterprise.inject.spi.CDI; import org.demoiselle.annotation.literal.NameQualifier;
/* * Demoiselle Framework * Copyright (C) 2010 SERPRO * ---------------------------------------------------------------------------- * This file is part of Demoiselle Framework. * * Demoiselle Framework is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License version 3 * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License version 3 * along with this program; if not, see <http://www.gnu.org/licenses/> * or write to the Free Software Foundation, Inc., 51 Franklin Street, * Fifth Floor, Boston, MA 02110-1301, USA. * ---------------------------------------------------------------------------- * Este arquivo é parte do Framework Demoiselle. * * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação * do Software Livre (FSF). * * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português * para maiores detalhes. * * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título * "LICENCA.txt", junto com esse programa. Se não, acesse <http://www.gnu.org/licenses/> * ou escreva para a Fundação do Software Livre (FSF) Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. */ package org.demoiselle.security; /** * <p> * Thrown when the user's credentials are invalid. * </p> * * @author SERPRO */ public class InvalidCredentialsException extends AuthenticationException { private static final long serialVersionUID = 1L; public InvalidCredentialsException() {
// Path: framework/src/main/java/org/demoiselle/annotation/literal/NameQualifier.java // @SuppressWarnings("all") // public class NameQualifier extends AnnotationLiteral<Name> implements Name { // // private static final long serialVersionUID = 1L; // // private final String value; // // /** // * Constructor with string value of name literal. // * // * @param value value of name literal. // */ // public NameQualifier(String value) { // this.value = value; // } // // @Override // public String value() { // return this.value; // } // } // Path: framework/src/main/java/org/demoiselle/security/InvalidCredentialsException.java import org.demoiselle.util.ResourceBundle; import javax.enterprise.inject.spi.CDI; import org.demoiselle.annotation.literal.NameQualifier; /* * Demoiselle Framework * Copyright (C) 2010 SERPRO * ---------------------------------------------------------------------------- * This file is part of Demoiselle Framework. * * Demoiselle Framework is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License version 3 * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License version 3 * along with this program; if not, see <http://www.gnu.org/licenses/> * or write to the Free Software Foundation, Inc., 51 Franklin Street, * Fifth Floor, Boston, MA 02110-1301, USA. * ---------------------------------------------------------------------------- * Este arquivo é parte do Framework Demoiselle. * * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação * do Software Livre (FSF). * * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português * para maiores detalhes. * * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título * "LICENCA.txt", junto com esse programa. Se não, acesse <http://www.gnu.org/licenses/> * ou escreva para a Fundação do Software Livre (FSF) Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. */ package org.demoiselle.security; /** * <p> * Thrown when the user's credentials are invalid. * </p> * * @author SERPRO */ public class InvalidCredentialsException extends AuthenticationException { private static final long serialVersionUID = 1L; public InvalidCredentialsException() {
super(CDI.current().select(ResourceBundle.class, new NameQualifier("demoiselle-core-bundle")).get().getString("invalid-credentials"));
demoiselle/framework3
framework/src/main/java/org/demoiselle/internal/implementation/AnnotatedMethodProcessor.java
// Path: framework/src/main/java/org/demoiselle/annotation/literal/NameQualifier.java // @SuppressWarnings("all") // public class NameQualifier extends AnnotationLiteral<Name> implements Name { // // private static final long serialVersionUID = 1L; // // private final String value; // // /** // * Constructor with string value of name literal. // * // * @param value value of name literal. // */ // public NameQualifier(String value) { // this.value = value; // } // // @Override // public String value() { // return this.value; // } // }
import org.demoiselle.stereotype.ApplicationException; import org.demoiselle.annotation.Priority; import org.demoiselle.annotation.literal.NameQualifier; import org.demoiselle.message.SeverityType; import org.demoiselle.util.ResourceBundle; import javax.enterprise.inject.spi.AnnotatedMethod; import javax.enterprise.inject.spi.CDI; import java.lang.reflect.InvocationTargetException; import java.util.logging.Logger; import static java.util.logging.Level.SEVERE;
} else { switch (ann.severity()) { case INFO: getLogger().info(cause.getMessage()); break; case WARN: getLogger().warning(cause.getMessage()); break; default: getLogger().log(SEVERE, getBundle().getString("processing-fail"), cause); break; } } } private static <T> Integer getPriority(AnnotatedMethod<T> annotatedMethod) { Integer priority = Priority.MIN_PRIORITY; Priority annotation = annotatedMethod.getAnnotation(Priority.class); if (annotation != null) { priority = annotation.value(); } return priority; } protected ResourceBundle getBundle() { if (bundle == null) {
// Path: framework/src/main/java/org/demoiselle/annotation/literal/NameQualifier.java // @SuppressWarnings("all") // public class NameQualifier extends AnnotationLiteral<Name> implements Name { // // private static final long serialVersionUID = 1L; // // private final String value; // // /** // * Constructor with string value of name literal. // * // * @param value value of name literal. // */ // public NameQualifier(String value) { // this.value = value; // } // // @Override // public String value() { // return this.value; // } // } // Path: framework/src/main/java/org/demoiselle/internal/implementation/AnnotatedMethodProcessor.java import org.demoiselle.stereotype.ApplicationException; import org.demoiselle.annotation.Priority; import org.demoiselle.annotation.literal.NameQualifier; import org.demoiselle.message.SeverityType; import org.demoiselle.util.ResourceBundle; import javax.enterprise.inject.spi.AnnotatedMethod; import javax.enterprise.inject.spi.CDI; import java.lang.reflect.InvocationTargetException; import java.util.logging.Logger; import static java.util.logging.Level.SEVERE; } else { switch (ann.severity()) { case INFO: getLogger().info(cause.getMessage()); break; case WARN: getLogger().warning(cause.getMessage()); break; default: getLogger().log(SEVERE, getBundle().getString("processing-fail"), cause); break; } } } private static <T> Integer getPriority(AnnotatedMethod<T> annotatedMethod) { Integer priority = Priority.MIN_PRIORITY; Priority annotation = annotatedMethod.getAnnotation(Priority.class); if (annotation != null) { priority = annotation.value(); } return priority; } protected ResourceBundle getBundle() { if (bundle == null) {
bundle = CDI.current().select(ResourceBundle.class, new NameQualifier("demoiselle-core-bundle")).get();
demoiselle/framework3
framework/src/main/java/org/demoiselle/internal/producer/AuthorizerProducer.java
// Path: framework/src/main/java/org/demoiselle/security/Authorizer.java // public interface Authorizer extends Serializable { // // /** // * <p> // * Checks if the logged user has a specific role. // * </p> // * // * @param role role to be checked. // * @return {@code true} if the user has the role. // * @throws Exception if the underlying permission checking mechanism throwns any other exception, // * just throw it and leave the security context implementation to handle it. // */ // boolean hasRole(String role) throws Exception; // // /** // * <p> // * Checks if the logged user has permission to execute a specific operation on a specific resource. // * </p> // * // * @param resource resource to be checked. // * @param operation operation to be checked. // * @return {@code true} if the user has the permission. // * @throws Exception if the underlying permission checking mechanism throwns any other exception, // * just throw it and leave the security context implementation to handle it. // */ // boolean hasPermission(String resource, String operation) throws Exception; // // }
import javax.enterprise.context.Dependent; import javax.enterprise.inject.Produces; import org.demoiselle.annotation.Strategy; import org.demoiselle.security.Authorizer;
/* * Demoiselle Framework * Copyright (C) 2010 SERPRO * ---------------------------------------------------------------------------- * This file is part of Demoiselle Framework. * * Demoiselle Framework is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License version 3 * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License version 3 * along with this program; if not, see <http://www.gnu.org/licenses/> * or write to the Free Software Foundation, Inc., 51 Franklin Street, * Fifth Floor, Boston, MA 02110-1301, USA. * ---------------------------------------------------------------------------- * Este arquivo é parte do Framework Demoiselle. * * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação * do Software Livre (FSF). * * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português * para maiores detalhes. * * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título * "LICENCA.txt", junto com esse programa. Se não, acesse <http://www.gnu.org/licenses/> * ou escreva para a Fundação do Software Livre (FSF) Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. */ package org.demoiselle.internal.producer; @Dependent public class AuthorizerProducer { @Produces @Strategy
// Path: framework/src/main/java/org/demoiselle/security/Authorizer.java // public interface Authorizer extends Serializable { // // /** // * <p> // * Checks if the logged user has a specific role. // * </p> // * // * @param role role to be checked. // * @return {@code true} if the user has the role. // * @throws Exception if the underlying permission checking mechanism throwns any other exception, // * just throw it and leave the security context implementation to handle it. // */ // boolean hasRole(String role) throws Exception; // // /** // * <p> // * Checks if the logged user has permission to execute a specific operation on a specific resource. // * </p> // * // * @param resource resource to be checked. // * @param operation operation to be checked. // * @return {@code true} if the user has the permission. // * @throws Exception if the underlying permission checking mechanism throwns any other exception, // * just throw it and leave the security context implementation to handle it. // */ // boolean hasPermission(String resource, String operation) throws Exception; // // } // Path: framework/src/main/java/org/demoiselle/internal/producer/AuthorizerProducer.java import javax.enterprise.context.Dependent; import javax.enterprise.inject.Produces; import org.demoiselle.annotation.Strategy; import org.demoiselle.security.Authorizer; /* * Demoiselle Framework * Copyright (C) 2010 SERPRO * ---------------------------------------------------------------------------- * This file is part of Demoiselle Framework. * * Demoiselle Framework is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License version 3 * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License version 3 * along with this program; if not, see <http://www.gnu.org/licenses/> * or write to the Free Software Foundation, Inc., 51 Franklin Street, * Fifth Floor, Boston, MA 02110-1301, USA. * ---------------------------------------------------------------------------- * Este arquivo é parte do Framework Demoiselle. * * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação * do Software Livre (FSF). * * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português * para maiores detalhes. * * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título * "LICENCA.txt", junto com esse programa. Se não, acesse <http://www.gnu.org/licenses/> * ou escreva para a Fundação do Software Livre (FSF) Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. */ package org.demoiselle.internal.producer; @Dependent public class AuthorizerProducer { @Produces @Strategy
public Authorizer create() {
demoiselle/framework3
bookmark/src/main/java/br/gov/serpro/demoiselle/bookmark/security/BookmarkAuthenticator.java
// Path: framework/src/main/java/org/demoiselle/security/InvalidCredentialsException.java // public class InvalidCredentialsException extends AuthenticationException { // // private static final long serialVersionUID = 1L; // // public InvalidCredentialsException() { // super(CDI.current().select(ResourceBundle.class, new NameQualifier("demoiselle-core-bundle")).get().getString("invalid-credentials")); // } // // /** // * <p> // * Constructs an <code>InvalidCredentialsException</code> with a message. // * </p> // * // * @param message exception message. // */ // public InvalidCredentialsException(String message) { // super(message); // } // // /** // * <p> // * Constructor with message and cause. // * </p> // * // * @param message exception message. // * @param cause exception cause. // */ // public InvalidCredentialsException(String message, Throwable cause) { // super(message, cause); // } // }
import org.demoiselle.annotation.Priority; import org.demoiselle.security.Authenticator; import org.demoiselle.security.InvalidCredentialsException; import org.demoiselle.servlet.security.Credentials; import javax.enterprise.context.SessionScoped; import javax.enterprise.inject.spi.CDI; import java.security.Principal;
package br.gov.serpro.demoiselle.bookmark.security; /** * @author SERPRO */ @SessionScoped @Priority(Priority.L3_PRIORITY) public class BookmarkAuthenticator implements Authenticator { private static final long serialVersionUID = -118515447020255993L; private Principal principal; /** * Authenticates any user since that password be "secret". * * @throws Exception */ @Override public void authenticate() throws Exception { Credentials credentials = CDI.current().select(Credentials.class).get(); if (credentials.getPassword().equals("secret")) { this.principal = credentials::getUsername; } else {
// Path: framework/src/main/java/org/demoiselle/security/InvalidCredentialsException.java // public class InvalidCredentialsException extends AuthenticationException { // // private static final long serialVersionUID = 1L; // // public InvalidCredentialsException() { // super(CDI.current().select(ResourceBundle.class, new NameQualifier("demoiselle-core-bundle")).get().getString("invalid-credentials")); // } // // /** // * <p> // * Constructs an <code>InvalidCredentialsException</code> with a message. // * </p> // * // * @param message exception message. // */ // public InvalidCredentialsException(String message) { // super(message); // } // // /** // * <p> // * Constructor with message and cause. // * </p> // * // * @param message exception message. // * @param cause exception cause. // */ // public InvalidCredentialsException(String message, Throwable cause) { // super(message, cause); // } // } // Path: bookmark/src/main/java/br/gov/serpro/demoiselle/bookmark/security/BookmarkAuthenticator.java import org.demoiselle.annotation.Priority; import org.demoiselle.security.Authenticator; import org.demoiselle.security.InvalidCredentialsException; import org.demoiselle.servlet.security.Credentials; import javax.enterprise.context.SessionScoped; import javax.enterprise.inject.spi.CDI; import java.security.Principal; package br.gov.serpro.demoiselle.bookmark.security; /** * @author SERPRO */ @SessionScoped @Priority(Priority.L3_PRIORITY) public class BookmarkAuthenticator implements Authenticator { private static final long serialVersionUID = -118515447020255993L; private Principal principal; /** * Authenticates any user since that password be "secret". * * @throws Exception */ @Override public void authenticate() throws Exception { Credentials credentials = CDI.current().select(Credentials.class).get(); if (credentials.getPassword().equals("secret")) { this.principal = credentials::getUsername; } else {
throw new InvalidCredentialsException();
demoiselle/framework3
framework/src/main/java/org/demoiselle/rest/internal/implementation/AuthenticationExceptionMapper.java
// Path: framework/src/main/java/org/demoiselle/annotation/literal/NameQualifier.java // @SuppressWarnings("all") // public class NameQualifier extends AnnotationLiteral<Name> implements Name { // // private static final long serialVersionUID = 1L; // // private final String value; // // /** // * Constructor with string value of name literal. // * // * @param value value of name literal. // */ // public NameQualifier(String value) { // this.value = value; // } // // @Override // public String value() { // return this.value; // } // }
import org.demoiselle.annotation.literal.NameQualifier; import org.demoiselle.security.AuthenticationException; import org.demoiselle.util.ResourceBundle; import javax.enterprise.inject.spi.CDI; import javax.ws.rs.core.Response; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Provider; import java.util.logging.Logger; import static java.util.logging.Level.FINE; import static javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED;
/* * Demoiselle Framework * Copyright (C) 2010 SERPRO * ---------------------------------------------------------------------------- * This file is part of Demoiselle Framework. * * Demoiselle Framework is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License version 3 * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License version 3 * along with this program; if not, see <http://www.gnu.org/licenses/> * or write to the Free Software Foundation, Inc., 51 Franklin Street, * Fifth Floor, Boston, MA 02110-1301, USA. * ---------------------------------------------------------------------------- * Este arquivo é parte do Framework Demoiselle. * * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação * do Software Livre (FSF). * * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português * para maiores detalhes. * * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título * "LICENCA.txt", junto com esse programa. Se não, acesse <http://www.gnu.org/licenses/> * ou escreva para a Fundação do Software Livre (FSF) Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. */ package org.demoiselle.rest.internal.implementation; /** * @author SERPRO */ @Provider public class AuthenticationExceptionMapper implements ExceptionMapper<AuthenticationException> { private transient ResourceBundle bundle; private transient Logger logger; @Override public Response toResponse(AuthenticationException exception) { int status = SC_UNAUTHORIZED; String message = getBundle().getString("mapping-violations", status); getLogger().log(FINE, message, exception); return Response.status(status).entity(exception.getMessage()).type("text/plain").build(); } private ResourceBundle getBundle() { if (bundle == null) {
// Path: framework/src/main/java/org/demoiselle/annotation/literal/NameQualifier.java // @SuppressWarnings("all") // public class NameQualifier extends AnnotationLiteral<Name> implements Name { // // private static final long serialVersionUID = 1L; // // private final String value; // // /** // * Constructor with string value of name literal. // * // * @param value value of name literal. // */ // public NameQualifier(String value) { // this.value = value; // } // // @Override // public String value() { // return this.value; // } // } // Path: framework/src/main/java/org/demoiselle/rest/internal/implementation/AuthenticationExceptionMapper.java import org.demoiselle.annotation.literal.NameQualifier; import org.demoiselle.security.AuthenticationException; import org.demoiselle.util.ResourceBundle; import javax.enterprise.inject.spi.CDI; import javax.ws.rs.core.Response; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Provider; import java.util.logging.Logger; import static java.util.logging.Level.FINE; import static javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED; /* * Demoiselle Framework * Copyright (C) 2010 SERPRO * ---------------------------------------------------------------------------- * This file is part of Demoiselle Framework. * * Demoiselle Framework is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License version 3 * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License version 3 * along with this program; if not, see <http://www.gnu.org/licenses/> * or write to the Free Software Foundation, Inc., 51 Franklin Street, * Fifth Floor, Boston, MA 02110-1301, USA. * ---------------------------------------------------------------------------- * Este arquivo é parte do Framework Demoiselle. * * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação * do Software Livre (FSF). * * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português * para maiores detalhes. * * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título * "LICENCA.txt", junto com esse programa. Se não, acesse <http://www.gnu.org/licenses/> * ou escreva para a Fundação do Software Livre (FSF) Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. */ package org.demoiselle.rest.internal.implementation; /** * @author SERPRO */ @Provider public class AuthenticationExceptionMapper implements ExceptionMapper<AuthenticationException> { private transient ResourceBundle bundle; private transient Logger logger; @Override public Response toResponse(AuthenticationException exception) { int status = SC_UNAUTHORIZED; String message = getBundle().getString("mapping-violations", status); getLogger().log(FINE, message, exception); return Response.status(status).entity(exception.getMessage()).type("text/plain").build(); } private ResourceBundle getBundle() { if (bundle == null) {
bundle = CDI.current().select(ResourceBundle.class, new NameQualifier("demoiselle-rest-bundle")).get();
t28hub/json2java4idea
core/src/test/java/io/t28/json2java/core/annotation/SuppressWarningsAnnotationPolicyTest.java
// Path: core/src/test/java/io/t28/json2java/core/Assertions.java // @Nonnull // @CheckReturnValue // public static JsonValueAssert assertThat(@Nullable JsonValue actual) { // return new JsonValueAssert(actual); // }
import com.squareup.javapoet.AnnotationSpec; import com.squareup.javapoet.TypeSpec; import org.junit.Before; import org.junit.Test; import static io.t28.json2java.core.Assertions.assertThat;
/* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.core.annotation; public class SuppressWarningsAnnotationPolicyTest { private SuppressWarningsAnnotationPolicy underTest; @Before public void setUp() throws Exception { underTest = new SuppressWarningsAnnotationPolicy("all"); } @Test public void applyShouldAddGeneratedAnnotation() throws Exception { // setup final TypeSpec.Builder builder = TypeSpec.classBuilder("Test"); // exercise underTest.apply(builder); // verify
// Path: core/src/test/java/io/t28/json2java/core/Assertions.java // @Nonnull // @CheckReturnValue // public static JsonValueAssert assertThat(@Nullable JsonValue actual) { // return new JsonValueAssert(actual); // } // Path: core/src/test/java/io/t28/json2java/core/annotation/SuppressWarningsAnnotationPolicyTest.java import com.squareup.javapoet.AnnotationSpec; import com.squareup.javapoet.TypeSpec; import org.junit.Before; import org.junit.Test; import static io.t28.json2java.core.Assertions.assertThat; /* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.core.annotation; public class SuppressWarningsAnnotationPolicyTest { private SuppressWarningsAnnotationPolicy underTest; @Before public void setUp() throws Exception { underTest = new SuppressWarningsAnnotationPolicy("all"); } @Test public void applyShouldAddGeneratedAnnotation() throws Exception { // setup final TypeSpec.Builder builder = TypeSpec.classBuilder("Test"); // exercise underTest.apply(builder); // verify
assertThat(builder.build())
t28hub/json2java4idea
idea/src/test/java/io/t28/json2java/idea/view/SettingsPanelTest.java
// Path: core/src/main/java/io/t28/json2java/core/Style.java // public enum Style { // NONE { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new ModelClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }, // GSON { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new GsonClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }, // JACKSON { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new JacksonClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }, // MOSHI { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new MoshiClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }; // // @Nonnull // @CheckReturnValue // abstract ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy); // // @Nonnull // @CheckReturnValue // public static Optional<Style> fromName(@Nonnull String name) { // return Stream.of(Style.values()) // .filter(style -> style.name().equalsIgnoreCase(name)) // .findFirst(); // } // // @Nonnull // @CheckReturnValue // public static Style fromName(@Nonnull String name, @Nonnull Style defaultStyle) { // return fromName(name).orElse(defaultStyle); // } // // public String get() { // return ""; // } // } // // Path: idea/src/main/java/io/t28/json2java/idea/Json2JavaBundle.java // public class Json2JavaBundle extends AbstractBundle { // private static final String BUNDLE = "messages.Json2Java4IdeaBundle"; // // public Json2JavaBundle() { // super(BUNDLE); // } // // @Nonnull // public static Json2JavaBundle getInstance() { // return new Json2JavaBundle(); // } // // @Nonnull // @CheckReturnValue // public String message(@Nonnull @PropertyKey(resourceBundle = BUNDLE) String key, @Nonnull Object... objects) { // return getMessage(key, objects); // } // }
import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.EditorFactory; import com.intellij.testFramework.fixtures.BareTestFixture; import com.intellij.testFramework.fixtures.IdeaTestFixtureFactory; import io.t28.json2java.core.Style; import io.t28.json2java.idea.Json2JavaBundle; import org.assertj.core.util.CheckReturnValue; import org.assertj.swing.dependency.jsr305.Nonnull; import org.assertj.swing.edt.GuiActionRunner; import org.assertj.swing.fixture.Containers; import org.assertj.swing.fixture.FrameFixture; import org.assertj.swing.fixture.JPanelFixture; import org.assertj.swing.fixture.JRadioButtonFixture; import org.assertj.swing.fixture.JTextComponentFixture; import org.jetbrains.annotations.PropertyKey; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import javax.swing.JRadioButton; import java.awt.event.ActionEvent; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify;
/* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.idea.view; @Ignore public class SettingsPanelTest {
// Path: core/src/main/java/io/t28/json2java/core/Style.java // public enum Style { // NONE { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new ModelClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }, // GSON { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new GsonClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }, // JACKSON { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new JacksonClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }, // MOSHI { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new MoshiClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }; // // @Nonnull // @CheckReturnValue // abstract ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy); // // @Nonnull // @CheckReturnValue // public static Optional<Style> fromName(@Nonnull String name) { // return Stream.of(Style.values()) // .filter(style -> style.name().equalsIgnoreCase(name)) // .findFirst(); // } // // @Nonnull // @CheckReturnValue // public static Style fromName(@Nonnull String name, @Nonnull Style defaultStyle) { // return fromName(name).orElse(defaultStyle); // } // // public String get() { // return ""; // } // } // // Path: idea/src/main/java/io/t28/json2java/idea/Json2JavaBundle.java // public class Json2JavaBundle extends AbstractBundle { // private static final String BUNDLE = "messages.Json2Java4IdeaBundle"; // // public Json2JavaBundle() { // super(BUNDLE); // } // // @Nonnull // public static Json2JavaBundle getInstance() { // return new Json2JavaBundle(); // } // // @Nonnull // @CheckReturnValue // public String message(@Nonnull @PropertyKey(resourceBundle = BUNDLE) String key, @Nonnull Object... objects) { // return getMessage(key, objects); // } // } // Path: idea/src/test/java/io/t28/json2java/idea/view/SettingsPanelTest.java import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.EditorFactory; import com.intellij.testFramework.fixtures.BareTestFixture; import com.intellij.testFramework.fixtures.IdeaTestFixtureFactory; import io.t28.json2java.core.Style; import io.t28.json2java.idea.Json2JavaBundle; import org.assertj.core.util.CheckReturnValue; import org.assertj.swing.dependency.jsr305.Nonnull; import org.assertj.swing.edt.GuiActionRunner; import org.assertj.swing.fixture.Containers; import org.assertj.swing.fixture.FrameFixture; import org.assertj.swing.fixture.JPanelFixture; import org.assertj.swing.fixture.JRadioButtonFixture; import org.assertj.swing.fixture.JTextComponentFixture; import org.jetbrains.annotations.PropertyKey; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import javax.swing.JRadioButton; import java.awt.event.ActionEvent; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; /* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.idea.view; @Ignore public class SettingsPanelTest {
private static Json2JavaBundle bundle;
t28hub/json2java4idea
idea/src/test/java/io/t28/json2java/idea/view/SettingsPanelTest.java
// Path: core/src/main/java/io/t28/json2java/core/Style.java // public enum Style { // NONE { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new ModelClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }, // GSON { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new GsonClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }, // JACKSON { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new JacksonClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }, // MOSHI { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new MoshiClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }; // // @Nonnull // @CheckReturnValue // abstract ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy); // // @Nonnull // @CheckReturnValue // public static Optional<Style> fromName(@Nonnull String name) { // return Stream.of(Style.values()) // .filter(style -> style.name().equalsIgnoreCase(name)) // .findFirst(); // } // // @Nonnull // @CheckReturnValue // public static Style fromName(@Nonnull String name, @Nonnull Style defaultStyle) { // return fromName(name).orElse(defaultStyle); // } // // public String get() { // return ""; // } // } // // Path: idea/src/main/java/io/t28/json2java/idea/Json2JavaBundle.java // public class Json2JavaBundle extends AbstractBundle { // private static final String BUNDLE = "messages.Json2Java4IdeaBundle"; // // public Json2JavaBundle() { // super(BUNDLE); // } // // @Nonnull // public static Json2JavaBundle getInstance() { // return new Json2JavaBundle(); // } // // @Nonnull // @CheckReturnValue // public String message(@Nonnull @PropertyKey(resourceBundle = BUNDLE) String key, @Nonnull Object... objects) { // return getMessage(key, objects); // } // }
import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.EditorFactory; import com.intellij.testFramework.fixtures.BareTestFixture; import com.intellij.testFramework.fixtures.IdeaTestFixtureFactory; import io.t28.json2java.core.Style; import io.t28.json2java.idea.Json2JavaBundle; import org.assertj.core.util.CheckReturnValue; import org.assertj.swing.dependency.jsr305.Nonnull; import org.assertj.swing.edt.GuiActionRunner; import org.assertj.swing.fixture.Containers; import org.assertj.swing.fixture.FrameFixture; import org.assertj.swing.fixture.JPanelFixture; import org.assertj.swing.fixture.JRadioButtonFixture; import org.assertj.swing.fixture.JTextComponentFixture; import org.jetbrains.annotations.PropertyKey; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import javax.swing.JRadioButton; import java.awt.event.ActionEvent; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify;
testFixture.tearDown(); } @Test public void disposeShouldReleaseEditor() throws Exception { // exercise application.invokeAndWait(() -> underTest.dispose()); // verify final Editor[] actual = EditorFactory.getInstance().getAllEditors(); assertThat(actual) .isEmpty(); } @Test public void actionPerformedShouldCallOnChanged() throws Exception { // setup final SettingsPanel underTest = spy(this.underTest); // exercise final ActionEvent event = mock(ActionEvent.class); underTest.actionPerformed(event); // verify verify(underTest).onChanged(); } @Test public void getStyleShouldReturnNoneByDefault() throws Exception { // exercise
// Path: core/src/main/java/io/t28/json2java/core/Style.java // public enum Style { // NONE { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new ModelClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }, // GSON { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new GsonClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }, // JACKSON { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new JacksonClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }, // MOSHI { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new MoshiClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }; // // @Nonnull // @CheckReturnValue // abstract ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy); // // @Nonnull // @CheckReturnValue // public static Optional<Style> fromName(@Nonnull String name) { // return Stream.of(Style.values()) // .filter(style -> style.name().equalsIgnoreCase(name)) // .findFirst(); // } // // @Nonnull // @CheckReturnValue // public static Style fromName(@Nonnull String name, @Nonnull Style defaultStyle) { // return fromName(name).orElse(defaultStyle); // } // // public String get() { // return ""; // } // } // // Path: idea/src/main/java/io/t28/json2java/idea/Json2JavaBundle.java // public class Json2JavaBundle extends AbstractBundle { // private static final String BUNDLE = "messages.Json2Java4IdeaBundle"; // // public Json2JavaBundle() { // super(BUNDLE); // } // // @Nonnull // public static Json2JavaBundle getInstance() { // return new Json2JavaBundle(); // } // // @Nonnull // @CheckReturnValue // public String message(@Nonnull @PropertyKey(resourceBundle = BUNDLE) String key, @Nonnull Object... objects) { // return getMessage(key, objects); // } // } // Path: idea/src/test/java/io/t28/json2java/idea/view/SettingsPanelTest.java import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.EditorFactory; import com.intellij.testFramework.fixtures.BareTestFixture; import com.intellij.testFramework.fixtures.IdeaTestFixtureFactory; import io.t28.json2java.core.Style; import io.t28.json2java.idea.Json2JavaBundle; import org.assertj.core.util.CheckReturnValue; import org.assertj.swing.dependency.jsr305.Nonnull; import org.assertj.swing.edt.GuiActionRunner; import org.assertj.swing.fixture.Containers; import org.assertj.swing.fixture.FrameFixture; import org.assertj.swing.fixture.JPanelFixture; import org.assertj.swing.fixture.JRadioButtonFixture; import org.assertj.swing.fixture.JTextComponentFixture; import org.jetbrains.annotations.PropertyKey; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import javax.swing.JRadioButton; import java.awt.event.ActionEvent; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; testFixture.tearDown(); } @Test public void disposeShouldReleaseEditor() throws Exception { // exercise application.invokeAndWait(() -> underTest.dispose()); // verify final Editor[] actual = EditorFactory.getInstance().getAllEditors(); assertThat(actual) .isEmpty(); } @Test public void actionPerformedShouldCallOnChanged() throws Exception { // setup final SettingsPanel underTest = spy(this.underTest); // exercise final ActionEvent event = mock(ActionEvent.class); underTest.actionPerformed(event); // verify verify(underTest).onChanged(); } @Test public void getStyleShouldReturnNoneByDefault() throws Exception { // exercise
final Style actual = underTest.getStyle();
t28hub/json2java4idea
core/src/test/java/io/t28/json2java/core/builder/JacksonClassBuilderTest.java
// Path: core/src/main/java/io/t28/json2java/core/naming/DefaultNamePolicy.java // public enum DefaultNamePolicy implements NamePolicy { // CLASS { // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // return format(name, CaseFormat.UPPER_CAMEL); // } // }, // METHOD { // private static final String BOOLEAN_PREFIX = "is"; // private static final String GENERAL_PREFIX = "get"; // // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // final StringBuilder builder = new StringBuilder(); // if (type.equals(TypeName.BOOLEAN) || type.equals(ClassName.get(Boolean.class))) { // builder.append(BOOLEAN_PREFIX); // } else { // builder.append(GENERAL_PREFIX); // } // return builder.append(format(name, CaseFormat.UPPER_CAMEL)) // .toString(); // } // }, // FIELD { // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // return format(name, CaseFormat.LOWER_CAMEL); // } // }, // PARAMETER { // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // return format(name, CaseFormat.LOWER_CAMEL); // } // }; // // private static final String NO_TEXT = ""; // private static final String DELIMITER = "_"; // private static final String DELIMITER_REGEX = "(_|-|\\s|\\.|:)"; // private static final String CAMEL_CASE_REGEX = "(?<!(^|[A-Z]))(?=[A-Z])|(?<!^)(?=[A-Z][a-z])"; // private static final String INVALID_IDENTIFIER_REGEX = "[^A-Za-z0-9_$]"; // // @Nonnull // @CheckReturnValue // public static String format(@Nonnull String name, @Nonnull CaseFormat format) { // final Matcher matcher = Pattern.compile(DELIMITER_REGEX).matcher(name); // final String pattern; // if (matcher.find()) { // pattern = DELIMITER_REGEX; // } else { // pattern = CAMEL_CASE_REGEX; // } // final String snakeCase = Stream.of(name.split(pattern)) // .map(Ascii::toLowerCase) // .map(part -> part.replaceAll(INVALID_IDENTIFIER_REGEX, NO_TEXT)) // .filter(part -> !Strings.isNullOrEmpty(part)) // .collect(Collectors.joining(DELIMITER)); // return CaseFormat.LOWER_UNDERSCORE.to(format, snakeCase); // } // } // // Path: core/src/test/java/io/t28/json2java/core/Assertions.java // @Nonnull // @CheckReturnValue // public static JsonValueAssert assertThat(@Nullable JsonValue actual) { // return new JsonValueAssert(actual); // }
import com.fasterxml.jackson.annotation.JsonProperty; import com.squareup.javapoet.AnnotationSpec; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.TypeName; import io.t28.json2java.core.naming.DefaultNamePolicy; import org.junit.Before; import org.junit.Test; import java.util.List; import static io.t28.json2java.core.Assertions.assertThat;
/* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.core.builder; public class JacksonClassBuilderTest { private JacksonClassBuilder underTest; @Before public void setUp() throws Exception { underTest = new JacksonClassBuilder(
// Path: core/src/main/java/io/t28/json2java/core/naming/DefaultNamePolicy.java // public enum DefaultNamePolicy implements NamePolicy { // CLASS { // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // return format(name, CaseFormat.UPPER_CAMEL); // } // }, // METHOD { // private static final String BOOLEAN_PREFIX = "is"; // private static final String GENERAL_PREFIX = "get"; // // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // final StringBuilder builder = new StringBuilder(); // if (type.equals(TypeName.BOOLEAN) || type.equals(ClassName.get(Boolean.class))) { // builder.append(BOOLEAN_PREFIX); // } else { // builder.append(GENERAL_PREFIX); // } // return builder.append(format(name, CaseFormat.UPPER_CAMEL)) // .toString(); // } // }, // FIELD { // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // return format(name, CaseFormat.LOWER_CAMEL); // } // }, // PARAMETER { // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // return format(name, CaseFormat.LOWER_CAMEL); // } // }; // // private static final String NO_TEXT = ""; // private static final String DELIMITER = "_"; // private static final String DELIMITER_REGEX = "(_|-|\\s|\\.|:)"; // private static final String CAMEL_CASE_REGEX = "(?<!(^|[A-Z]))(?=[A-Z])|(?<!^)(?=[A-Z][a-z])"; // private static final String INVALID_IDENTIFIER_REGEX = "[^A-Za-z0-9_$]"; // // @Nonnull // @CheckReturnValue // public static String format(@Nonnull String name, @Nonnull CaseFormat format) { // final Matcher matcher = Pattern.compile(DELIMITER_REGEX).matcher(name); // final String pattern; // if (matcher.find()) { // pattern = DELIMITER_REGEX; // } else { // pattern = CAMEL_CASE_REGEX; // } // final String snakeCase = Stream.of(name.split(pattern)) // .map(Ascii::toLowerCase) // .map(part -> part.replaceAll(INVALID_IDENTIFIER_REGEX, NO_TEXT)) // .filter(part -> !Strings.isNullOrEmpty(part)) // .collect(Collectors.joining(DELIMITER)); // return CaseFormat.LOWER_UNDERSCORE.to(format, snakeCase); // } // } // // Path: core/src/test/java/io/t28/json2java/core/Assertions.java // @Nonnull // @CheckReturnValue // public static JsonValueAssert assertThat(@Nullable JsonValue actual) { // return new JsonValueAssert(actual); // } // Path: core/src/test/java/io/t28/json2java/core/builder/JacksonClassBuilderTest.java import com.fasterxml.jackson.annotation.JsonProperty; import com.squareup.javapoet.AnnotationSpec; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.TypeName; import io.t28.json2java.core.naming.DefaultNamePolicy; import org.junit.Before; import org.junit.Test; import java.util.List; import static io.t28.json2java.core.Assertions.assertThat; /* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.core.builder; public class JacksonClassBuilderTest { private JacksonClassBuilder underTest; @Before public void setUp() throws Exception { underTest = new JacksonClassBuilder(
DefaultNamePolicy.FIELD,
t28hub/json2java4idea
core/src/test/java/io/t28/json2java/core/builder/JacksonClassBuilderTest.java
// Path: core/src/main/java/io/t28/json2java/core/naming/DefaultNamePolicy.java // public enum DefaultNamePolicy implements NamePolicy { // CLASS { // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // return format(name, CaseFormat.UPPER_CAMEL); // } // }, // METHOD { // private static final String BOOLEAN_PREFIX = "is"; // private static final String GENERAL_PREFIX = "get"; // // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // final StringBuilder builder = new StringBuilder(); // if (type.equals(TypeName.BOOLEAN) || type.equals(ClassName.get(Boolean.class))) { // builder.append(BOOLEAN_PREFIX); // } else { // builder.append(GENERAL_PREFIX); // } // return builder.append(format(name, CaseFormat.UPPER_CAMEL)) // .toString(); // } // }, // FIELD { // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // return format(name, CaseFormat.LOWER_CAMEL); // } // }, // PARAMETER { // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // return format(name, CaseFormat.LOWER_CAMEL); // } // }; // // private static final String NO_TEXT = ""; // private static final String DELIMITER = "_"; // private static final String DELIMITER_REGEX = "(_|-|\\s|\\.|:)"; // private static final String CAMEL_CASE_REGEX = "(?<!(^|[A-Z]))(?=[A-Z])|(?<!^)(?=[A-Z][a-z])"; // private static final String INVALID_IDENTIFIER_REGEX = "[^A-Za-z0-9_$]"; // // @Nonnull // @CheckReturnValue // public static String format(@Nonnull String name, @Nonnull CaseFormat format) { // final Matcher matcher = Pattern.compile(DELIMITER_REGEX).matcher(name); // final String pattern; // if (matcher.find()) { // pattern = DELIMITER_REGEX; // } else { // pattern = CAMEL_CASE_REGEX; // } // final String snakeCase = Stream.of(name.split(pattern)) // .map(Ascii::toLowerCase) // .map(part -> part.replaceAll(INVALID_IDENTIFIER_REGEX, NO_TEXT)) // .filter(part -> !Strings.isNullOrEmpty(part)) // .collect(Collectors.joining(DELIMITER)); // return CaseFormat.LOWER_UNDERSCORE.to(format, snakeCase); // } // } // // Path: core/src/test/java/io/t28/json2java/core/Assertions.java // @Nonnull // @CheckReturnValue // public static JsonValueAssert assertThat(@Nullable JsonValue actual) { // return new JsonValueAssert(actual); // }
import com.fasterxml.jackson.annotation.JsonProperty; import com.squareup.javapoet.AnnotationSpec; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.TypeName; import io.t28.json2java.core.naming.DefaultNamePolicy; import org.junit.Before; import org.junit.Test; import java.util.List; import static io.t28.json2java.core.Assertions.assertThat;
/* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.core.builder; public class JacksonClassBuilderTest { private JacksonClassBuilder underTest; @Before public void setUp() throws Exception { underTest = new JacksonClassBuilder( DefaultNamePolicy.FIELD, DefaultNamePolicy.METHOD, DefaultNamePolicy.PARAMETER ); } @Test public void buildFields() throws Exception { // setup underTest.addProperty("foo", TypeName.INT) .addProperty("bar", TypeName.OBJECT) .addProperty("baz", TypeName.BOOLEAN); // exercise final List<FieldSpec> actual = underTest.buildFields(); // verify
// Path: core/src/main/java/io/t28/json2java/core/naming/DefaultNamePolicy.java // public enum DefaultNamePolicy implements NamePolicy { // CLASS { // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // return format(name, CaseFormat.UPPER_CAMEL); // } // }, // METHOD { // private static final String BOOLEAN_PREFIX = "is"; // private static final String GENERAL_PREFIX = "get"; // // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // final StringBuilder builder = new StringBuilder(); // if (type.equals(TypeName.BOOLEAN) || type.equals(ClassName.get(Boolean.class))) { // builder.append(BOOLEAN_PREFIX); // } else { // builder.append(GENERAL_PREFIX); // } // return builder.append(format(name, CaseFormat.UPPER_CAMEL)) // .toString(); // } // }, // FIELD { // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // return format(name, CaseFormat.LOWER_CAMEL); // } // }, // PARAMETER { // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // return format(name, CaseFormat.LOWER_CAMEL); // } // }; // // private static final String NO_TEXT = ""; // private static final String DELIMITER = "_"; // private static final String DELIMITER_REGEX = "(_|-|\\s|\\.|:)"; // private static final String CAMEL_CASE_REGEX = "(?<!(^|[A-Z]))(?=[A-Z])|(?<!^)(?=[A-Z][a-z])"; // private static final String INVALID_IDENTIFIER_REGEX = "[^A-Za-z0-9_$]"; // // @Nonnull // @CheckReturnValue // public static String format(@Nonnull String name, @Nonnull CaseFormat format) { // final Matcher matcher = Pattern.compile(DELIMITER_REGEX).matcher(name); // final String pattern; // if (matcher.find()) { // pattern = DELIMITER_REGEX; // } else { // pattern = CAMEL_CASE_REGEX; // } // final String snakeCase = Stream.of(name.split(pattern)) // .map(Ascii::toLowerCase) // .map(part -> part.replaceAll(INVALID_IDENTIFIER_REGEX, NO_TEXT)) // .filter(part -> !Strings.isNullOrEmpty(part)) // .collect(Collectors.joining(DELIMITER)); // return CaseFormat.LOWER_UNDERSCORE.to(format, snakeCase); // } // } // // Path: core/src/test/java/io/t28/json2java/core/Assertions.java // @Nonnull // @CheckReturnValue // public static JsonValueAssert assertThat(@Nullable JsonValue actual) { // return new JsonValueAssert(actual); // } // Path: core/src/test/java/io/t28/json2java/core/builder/JacksonClassBuilderTest.java import com.fasterxml.jackson.annotation.JsonProperty; import com.squareup.javapoet.AnnotationSpec; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.TypeName; import io.t28.json2java.core.naming.DefaultNamePolicy; import org.junit.Before; import org.junit.Test; import java.util.List; import static io.t28.json2java.core.Assertions.assertThat; /* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.core.builder; public class JacksonClassBuilderTest { private JacksonClassBuilder underTest; @Before public void setUp() throws Exception { underTest = new JacksonClassBuilder( DefaultNamePolicy.FIELD, DefaultNamePolicy.METHOD, DefaultNamePolicy.PARAMETER ); } @Test public void buildFields() throws Exception { // setup underTest.addProperty("foo", TypeName.INT) .addProperty("bar", TypeName.OBJECT) .addProperty("baz", TypeName.BOOLEAN); // exercise final List<FieldSpec> actual = underTest.buildFields(); // verify
assertThat(actual)
t28hub/json2java4idea
core/src/test/java/io/t28/json2java/core/json/JsonStringTest.java
// Path: core/src/test/java/io/t28/json2java/core/Assertions.java // @Nonnull // @CheckReturnValue // public static JsonValueAssert assertThat(@Nullable JsonValue actual) { // return new JsonValueAssert(actual); // }
import com.squareup.javapoet.ClassName; import com.squareup.javapoet.TypeName; import org.junit.Before; import org.junit.Test; import static io.t28.json2java.core.Assertions.assertThat;
/* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.core.json; public class JsonStringTest { private JsonString underTest; @Before public void setUp() throws Exception { underTest = new JsonString("foo"); } @Test public void getType() throws Exception { // exercise final TypeName actual = underTest.getType(); // verify
// Path: core/src/test/java/io/t28/json2java/core/Assertions.java // @Nonnull // @CheckReturnValue // public static JsonValueAssert assertThat(@Nullable JsonValue actual) { // return new JsonValueAssert(actual); // } // Path: core/src/test/java/io/t28/json2java/core/json/JsonStringTest.java import com.squareup.javapoet.ClassName; import com.squareup.javapoet.TypeName; import org.junit.Before; import org.junit.Test; import static io.t28.json2java.core.Assertions.assertThat; /* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.core.json; public class JsonStringTest { private JsonString underTest; @Before public void setUp() throws Exception { underTest = new JsonString("foo"); } @Test public void getType() throws Exception { // exercise final TypeName actual = underTest.getType(); // verify
assertThat(actual)
t28hub/json2java4idea
idea/src/test/java/io/t28/json2java/idea/setting/PersistentJson2JavaSettingsTest.java
// Path: core/src/main/java/io/t28/json2java/core/Style.java // public enum Style { // NONE { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new ModelClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }, // GSON { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new GsonClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }, // JACKSON { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new JacksonClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }, // MOSHI { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new MoshiClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }; // // @Nonnull // @CheckReturnValue // abstract ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy); // // @Nonnull // @CheckReturnValue // public static Optional<Style> fromName(@Nonnull String name) { // return Stream.of(Style.values()) // .filter(style -> style.name().equalsIgnoreCase(name)) // .findFirst(); // } // // @Nonnull // @CheckReturnValue // public static Style fromName(@Nonnull String name, @Nonnull Style defaultStyle) { // return fromName(name).orElse(defaultStyle); // } // // public String get() { // return ""; // } // } // // Path: idea/src/test/java/io/t28/json2java/idea/Assertions.java // @Nonnull // @CheckReturnValue // public static ElementAssert assertThat(@Nullable Element actual) { // return new ElementAssert(actual); // }
import io.t28.json2java.core.Style; import org.jdom.Element; import org.junit.Before; import org.junit.Test; import static io.t28.json2java.idea.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
/* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.idea.setting; public class PersistentJson2JavaSettingsTest { private PersistentJson2JavaSettings underTest; @Before public void setUp() throws Exception { underTest = new PersistentJson2JavaSettings(); } @Test public void getStateShouldReturnElement() throws Exception { // setup
// Path: core/src/main/java/io/t28/json2java/core/Style.java // public enum Style { // NONE { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new ModelClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }, // GSON { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new GsonClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }, // JACKSON { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new JacksonClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }, // MOSHI { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new MoshiClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }; // // @Nonnull // @CheckReturnValue // abstract ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy); // // @Nonnull // @CheckReturnValue // public static Optional<Style> fromName(@Nonnull String name) { // return Stream.of(Style.values()) // .filter(style -> style.name().equalsIgnoreCase(name)) // .findFirst(); // } // // @Nonnull // @CheckReturnValue // public static Style fromName(@Nonnull String name, @Nonnull Style defaultStyle) { // return fromName(name).orElse(defaultStyle); // } // // public String get() { // return ""; // } // } // // Path: idea/src/test/java/io/t28/json2java/idea/Assertions.java // @Nonnull // @CheckReturnValue // public static ElementAssert assertThat(@Nullable Element actual) { // return new ElementAssert(actual); // } // Path: idea/src/test/java/io/t28/json2java/idea/setting/PersistentJson2JavaSettingsTest.java import io.t28.json2java.core.Style; import org.jdom.Element; import org.junit.Before; import org.junit.Test; import static io.t28.json2java.idea.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat; /* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.idea.setting; public class PersistentJson2JavaSettingsTest { private PersistentJson2JavaSettings underTest; @Before public void setUp() throws Exception { underTest = new PersistentJson2JavaSettings(); } @Test public void getStateShouldReturnElement() throws Exception { // setup
underTest.setStyle(Style.GSON)
t28hub/json2java4idea
idea/src/test/java/io/t28/json2java/idea/setting/PersistentJson2JavaSettingsTest.java
// Path: core/src/main/java/io/t28/json2java/core/Style.java // public enum Style { // NONE { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new ModelClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }, // GSON { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new GsonClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }, // JACKSON { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new JacksonClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }, // MOSHI { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new MoshiClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }; // // @Nonnull // @CheckReturnValue // abstract ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy); // // @Nonnull // @CheckReturnValue // public static Optional<Style> fromName(@Nonnull String name) { // return Stream.of(Style.values()) // .filter(style -> style.name().equalsIgnoreCase(name)) // .findFirst(); // } // // @Nonnull // @CheckReturnValue // public static Style fromName(@Nonnull String name, @Nonnull Style defaultStyle) { // return fromName(name).orElse(defaultStyle); // } // // public String get() { // return ""; // } // } // // Path: idea/src/test/java/io/t28/json2java/idea/Assertions.java // @Nonnull // @CheckReturnValue // public static ElementAssert assertThat(@Nullable Element actual) { // return new ElementAssert(actual); // }
import io.t28.json2java.core.Style; import org.jdom.Element; import org.junit.Before; import org.junit.Test; import static io.t28.json2java.idea.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
/* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.idea.setting; public class PersistentJson2JavaSettingsTest { private PersistentJson2JavaSettings underTest; @Before public void setUp() throws Exception { underTest = new PersistentJson2JavaSettings(); } @Test public void getStateShouldReturnElement() throws Exception { // setup underTest.setStyle(Style.GSON) .setClassNamePrefix("Foo") .setClassNameSuffix("Bar") .setGeneratedAnnotationEnabled(true) .setSuppressWarningsAnnotationEnabled(false); // exercise final Element actual = underTest.getState(); // verify
// Path: core/src/main/java/io/t28/json2java/core/Style.java // public enum Style { // NONE { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new ModelClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }, // GSON { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new GsonClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }, // JACKSON { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new JacksonClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }, // MOSHI { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new MoshiClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }; // // @Nonnull // @CheckReturnValue // abstract ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy); // // @Nonnull // @CheckReturnValue // public static Optional<Style> fromName(@Nonnull String name) { // return Stream.of(Style.values()) // .filter(style -> style.name().equalsIgnoreCase(name)) // .findFirst(); // } // // @Nonnull // @CheckReturnValue // public static Style fromName(@Nonnull String name, @Nonnull Style defaultStyle) { // return fromName(name).orElse(defaultStyle); // } // // public String get() { // return ""; // } // } // // Path: idea/src/test/java/io/t28/json2java/idea/Assertions.java // @Nonnull // @CheckReturnValue // public static ElementAssert assertThat(@Nullable Element actual) { // return new ElementAssert(actual); // } // Path: idea/src/test/java/io/t28/json2java/idea/setting/PersistentJson2JavaSettingsTest.java import io.t28.json2java.core.Style; import org.jdom.Element; import org.junit.Before; import org.junit.Test; import static io.t28.json2java.idea.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat; /* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.idea.setting; public class PersistentJson2JavaSettingsTest { private PersistentJson2JavaSettings underTest; @Before public void setUp() throws Exception { underTest = new PersistentJson2JavaSettings(); } @Test public void getStateShouldReturnElement() throws Exception { // setup underTest.setStyle(Style.GSON) .setClassNamePrefix("Foo") .setClassNameSuffix("Bar") .setGeneratedAnnotationEnabled(true) .setSuppressWarningsAnnotationEnabled(false); // exercise final Element actual = underTest.getState(); // verify
assertThat(actual)
t28hub/json2java4idea
idea/src/main/java/io/t28/json2java/idea/setting/Json2JavaSettings.java
// Path: core/src/main/java/io/t28/json2java/core/Style.java // public enum Style { // NONE { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new ModelClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }, // GSON { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new GsonClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }, // JACKSON { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new JacksonClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }, // MOSHI { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new MoshiClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }; // // @Nonnull // @CheckReturnValue // abstract ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy); // // @Nonnull // @CheckReturnValue // public static Optional<Style> fromName(@Nonnull String name) { // return Stream.of(Style.values()) // .filter(style -> style.name().equalsIgnoreCase(name)) // .findFirst(); // } // // @Nonnull // @CheckReturnValue // public static Style fromName(@Nonnull String name, @Nonnull Style defaultStyle) { // return fromName(name).orElse(defaultStyle); // } // // public String get() { // return ""; // } // }
import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.project.Project; import io.t28.json2java.core.Style; import javax.annotation.CheckReturnValue; import javax.annotation.Nonnull;
/* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.idea.setting; public interface Json2JavaSettings { @Nonnull @CheckReturnValue static Json2JavaSettings getInstance() { return new TemporaryJson2JavaSettings(); } @Nonnull @CheckReturnValue static Json2JavaSettings getInstance(@Nonnull Project project) { return ServiceManager.getService(project, Json2JavaSettings.class); } @Nonnull @CheckReturnValue
// Path: core/src/main/java/io/t28/json2java/core/Style.java // public enum Style { // NONE { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new ModelClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }, // GSON { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new GsonClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }, // JACKSON { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new JacksonClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }, // MOSHI { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new MoshiClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }; // // @Nonnull // @CheckReturnValue // abstract ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy); // // @Nonnull // @CheckReturnValue // public static Optional<Style> fromName(@Nonnull String name) { // return Stream.of(Style.values()) // .filter(style -> style.name().equalsIgnoreCase(name)) // .findFirst(); // } // // @Nonnull // @CheckReturnValue // public static Style fromName(@Nonnull String name, @Nonnull Style defaultStyle) { // return fromName(name).orElse(defaultStyle); // } // // public String get() { // return ""; // } // } // Path: idea/src/main/java/io/t28/json2java/idea/setting/Json2JavaSettings.java import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.project.Project; import io.t28.json2java.core.Style; import javax.annotation.CheckReturnValue; import javax.annotation.Nonnull; /* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.idea.setting; public interface Json2JavaSettings { @Nonnull @CheckReturnValue static Json2JavaSettings getInstance() { return new TemporaryJson2JavaSettings(); } @Nonnull @CheckReturnValue static Json2JavaSettings getInstance(@Nonnull Project project) { return ServiceManager.getService(project, Json2JavaSettings.class); } @Nonnull @CheckReturnValue
Style getStyle();
t28hub/json2java4idea
idea/src/main/java/io/t28/json2java/idea/naming/ClassNamePolicy.java
// Path: core/src/main/java/io/t28/json2java/core/naming/DefaultNamePolicy.java // public enum DefaultNamePolicy implements NamePolicy { // CLASS { // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // return format(name, CaseFormat.UPPER_CAMEL); // } // }, // METHOD { // private static final String BOOLEAN_PREFIX = "is"; // private static final String GENERAL_PREFIX = "get"; // // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // final StringBuilder builder = new StringBuilder(); // if (type.equals(TypeName.BOOLEAN) || type.equals(ClassName.get(Boolean.class))) { // builder.append(BOOLEAN_PREFIX); // } else { // builder.append(GENERAL_PREFIX); // } // return builder.append(format(name, CaseFormat.UPPER_CAMEL)) // .toString(); // } // }, // FIELD { // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // return format(name, CaseFormat.LOWER_CAMEL); // } // }, // PARAMETER { // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // return format(name, CaseFormat.LOWER_CAMEL); // } // }; // // private static final String NO_TEXT = ""; // private static final String DELIMITER = "_"; // private static final String DELIMITER_REGEX = "(_|-|\\s|\\.|:)"; // private static final String CAMEL_CASE_REGEX = "(?<!(^|[A-Z]))(?=[A-Z])|(?<!^)(?=[A-Z][a-z])"; // private static final String INVALID_IDENTIFIER_REGEX = "[^A-Za-z0-9_$]"; // // @Nonnull // @CheckReturnValue // public static String format(@Nonnull String name, @Nonnull CaseFormat format) { // final Matcher matcher = Pattern.compile(DELIMITER_REGEX).matcher(name); // final String pattern; // if (matcher.find()) { // pattern = DELIMITER_REGEX; // } else { // pattern = CAMEL_CASE_REGEX; // } // final String snakeCase = Stream.of(name.split(pattern)) // .map(Ascii::toLowerCase) // .map(part -> part.replaceAll(INVALID_IDENTIFIER_REGEX, NO_TEXT)) // .filter(part -> !Strings.isNullOrEmpty(part)) // .collect(Collectors.joining(DELIMITER)); // return CaseFormat.LOWER_UNDERSCORE.to(format, snakeCase); // } // } // // Path: core/src/main/java/io/t28/json2java/core/naming/NamePolicy.java // public interface NamePolicy { // @Nonnull // @CheckReturnValue // String convert(@Nonnull String name, @Nonnull TypeName type); // }
import com.google.inject.Inject; import com.intellij.psi.PsiNameHelper; import com.squareup.javapoet.TypeName; import io.t28.json2java.core.naming.DefaultNamePolicy; import io.t28.json2java.core.naming.NamePolicy; import javax.annotation.Nonnull;
/* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.idea.naming; public class ClassNamePolicy implements NamePolicy { private final PsiNameHelper nameHelper; private final String prefix; private final String suffix; @Inject public ClassNamePolicy(@Nonnull PsiNameHelper nameHelper, @Nonnull String prefix, @Nonnull String suffix) { this.nameHelper = nameHelper; this.prefix = prefix; this.suffix = suffix; } @Nonnull @Override public String convert(@Nonnull String name, @Nonnull TypeName type) { final StringBuilder builder = new StringBuilder(); builder.append(prefix)
// Path: core/src/main/java/io/t28/json2java/core/naming/DefaultNamePolicy.java // public enum DefaultNamePolicy implements NamePolicy { // CLASS { // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // return format(name, CaseFormat.UPPER_CAMEL); // } // }, // METHOD { // private static final String BOOLEAN_PREFIX = "is"; // private static final String GENERAL_PREFIX = "get"; // // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // final StringBuilder builder = new StringBuilder(); // if (type.equals(TypeName.BOOLEAN) || type.equals(ClassName.get(Boolean.class))) { // builder.append(BOOLEAN_PREFIX); // } else { // builder.append(GENERAL_PREFIX); // } // return builder.append(format(name, CaseFormat.UPPER_CAMEL)) // .toString(); // } // }, // FIELD { // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // return format(name, CaseFormat.LOWER_CAMEL); // } // }, // PARAMETER { // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // return format(name, CaseFormat.LOWER_CAMEL); // } // }; // // private static final String NO_TEXT = ""; // private static final String DELIMITER = "_"; // private static final String DELIMITER_REGEX = "(_|-|\\s|\\.|:)"; // private static final String CAMEL_CASE_REGEX = "(?<!(^|[A-Z]))(?=[A-Z])|(?<!^)(?=[A-Z][a-z])"; // private static final String INVALID_IDENTIFIER_REGEX = "[^A-Za-z0-9_$]"; // // @Nonnull // @CheckReturnValue // public static String format(@Nonnull String name, @Nonnull CaseFormat format) { // final Matcher matcher = Pattern.compile(DELIMITER_REGEX).matcher(name); // final String pattern; // if (matcher.find()) { // pattern = DELIMITER_REGEX; // } else { // pattern = CAMEL_CASE_REGEX; // } // final String snakeCase = Stream.of(name.split(pattern)) // .map(Ascii::toLowerCase) // .map(part -> part.replaceAll(INVALID_IDENTIFIER_REGEX, NO_TEXT)) // .filter(part -> !Strings.isNullOrEmpty(part)) // .collect(Collectors.joining(DELIMITER)); // return CaseFormat.LOWER_UNDERSCORE.to(format, snakeCase); // } // } // // Path: core/src/main/java/io/t28/json2java/core/naming/NamePolicy.java // public interface NamePolicy { // @Nonnull // @CheckReturnValue // String convert(@Nonnull String name, @Nonnull TypeName type); // } // Path: idea/src/main/java/io/t28/json2java/idea/naming/ClassNamePolicy.java import com.google.inject.Inject; import com.intellij.psi.PsiNameHelper; import com.squareup.javapoet.TypeName; import io.t28.json2java.core.naming.DefaultNamePolicy; import io.t28.json2java.core.naming.NamePolicy; import javax.annotation.Nonnull; /* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.idea.naming; public class ClassNamePolicy implements NamePolicy { private final PsiNameHelper nameHelper; private final String prefix; private final String suffix; @Inject public ClassNamePolicy(@Nonnull PsiNameHelper nameHelper, @Nonnull String prefix, @Nonnull String suffix) { this.nameHelper = nameHelper; this.prefix = prefix; this.suffix = suffix; } @Nonnull @Override public String convert(@Nonnull String name, @Nonnull TypeName type) { final StringBuilder builder = new StringBuilder(); builder.append(prefix)
.append(DefaultNamePolicy.CLASS.convert(name, type))
t28hub/json2java4idea
core/src/test/java/io/t28/json2java/core/io/JsonParserImplTest.java
// Path: core/src/main/java/io/t28/json2java/core/io/JsonParserImpl.java // public class JsonParserImpl implements JsonParser { // private final ObjectMapper mapper; // // public JsonParserImpl() { // this(new ObjectMapper()); // } // // @VisibleForTesting // JsonParserImpl(@Nonnull ObjectMapper mapper) { // this.mapper = mapper; // } // // @Nonnull // @Override // public JsonValue parse(@Nonnull String json) throws JsonParseException { // try { // final Object parsed = mapper.readValue(json, Object.class); // return JsonValue.wrap(parsed); // } catch (IOException e) { // throw new JsonParseException("Unable to parse a JSON string(" + json + ")", e); // } // } // } // // Path: core/src/main/java/io/t28/json2java/core/io/exception/JsonParseException.java // public class JsonParseException extends IOException { // private static final long serialVersionUID = 1477109671450199015L; // // public JsonParseException(@Nonnull String message, @Nonnull Throwable cause) { // super(message, cause); // } // } // // Path: core/src/main/java/io/t28/json2java/core/json/JsonValue.java // public abstract class JsonValue { // @Nonnull // @CheckReturnValue // public static JsonValue wrap(@Nullable Object value) { // return Stream.of(ValueType.values()) // .filter(type -> type.isAcceptable(value)) // .findFirst() // .orElseThrow(() -> new IllegalArgumentException("Unsupported type of value(" + value + ")")) // .wrap(value); // } // // @Nonnull // public abstract TypeName getType(); // // public abstract Object getValue(); // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("type", getType()) // .add("value", getValue()) // .toString(); // } // // @CheckReturnValue // public boolean isNull() { // return this instanceof JsonNull; // } // // @CheckReturnValue // public boolean isBoolean() { // return this instanceof JsonBoolean; // } // // @CheckReturnValue // public boolean isNumber() { // return this instanceof JsonNumber; // } // // @CheckReturnValue // public boolean isString() { // return this instanceof JsonString; // } // // @CheckReturnValue // public boolean isArray() { // return this instanceof JsonArray; // } // // @CheckReturnValue // public boolean isObject() { // return this instanceof JsonObject; // } // // @Nonnull // @CheckReturnValue // public JsonNull asNull() { // if (isNull()) { // return (JsonNull) this; // } // throw new IllegalStateException("This value is not a null"); // } // // @Nonnull // @CheckReturnValue // public JsonBoolean asBoolean() { // if (isBoolean()) { // return (JsonBoolean) this; // } // throw new IllegalStateException("This value is not a boolean"); // } // // @Nonnull // @CheckReturnValue // public JsonNumber asNumber() { // if (isNumber()) { // return (JsonNumber) this; // } // throw new IllegalStateException("This value is not a number"); // } // // @Nonnull // @CheckReturnValue // public JsonString asString() { // if (isString()) { // return (JsonString) this; // } // throw new IllegalStateException("This value is not a string"); // } // // @Nonnull // @CheckReturnValue // public JsonArray asArray() { // if (isArray()) { // return (JsonArray) this; // } // throw new IllegalStateException("This value is not an array"); // } // // @Nonnull // @CheckReturnValue // public JsonObject asObject() { // if (isObject()) { // return (JsonObject) this; // } // throw new IllegalStateException("This value is not an object"); // } // } // // Path: core/src/test/java/io/t28/json2java/core/Assertions.java // @Nonnull // @CheckReturnValue // public static JsonValueAssert assertThat(@Nullable JsonValue actual) { // return new JsonValueAssert(actual); // }
import static io.t28.json2java.core.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.spy; import com.fasterxml.jackson.databind.ObjectMapper; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import io.t28.json2java.core.io.JsonParserImpl; import io.t28.json2java.core.io.exception.JsonParseException; import io.t28.json2java.core.json.JsonValue; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.util.Collections; import java.util.List; import java.util.Map;
/* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.core.io; @SuppressWarnings("ResultOfMethodCallIgnored") public class JsonParserImplTest { private ObjectMapper mapper;
// Path: core/src/main/java/io/t28/json2java/core/io/JsonParserImpl.java // public class JsonParserImpl implements JsonParser { // private final ObjectMapper mapper; // // public JsonParserImpl() { // this(new ObjectMapper()); // } // // @VisibleForTesting // JsonParserImpl(@Nonnull ObjectMapper mapper) { // this.mapper = mapper; // } // // @Nonnull // @Override // public JsonValue parse(@Nonnull String json) throws JsonParseException { // try { // final Object parsed = mapper.readValue(json, Object.class); // return JsonValue.wrap(parsed); // } catch (IOException e) { // throw new JsonParseException("Unable to parse a JSON string(" + json + ")", e); // } // } // } // // Path: core/src/main/java/io/t28/json2java/core/io/exception/JsonParseException.java // public class JsonParseException extends IOException { // private static final long serialVersionUID = 1477109671450199015L; // // public JsonParseException(@Nonnull String message, @Nonnull Throwable cause) { // super(message, cause); // } // } // // Path: core/src/main/java/io/t28/json2java/core/json/JsonValue.java // public abstract class JsonValue { // @Nonnull // @CheckReturnValue // public static JsonValue wrap(@Nullable Object value) { // return Stream.of(ValueType.values()) // .filter(type -> type.isAcceptable(value)) // .findFirst() // .orElseThrow(() -> new IllegalArgumentException("Unsupported type of value(" + value + ")")) // .wrap(value); // } // // @Nonnull // public abstract TypeName getType(); // // public abstract Object getValue(); // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("type", getType()) // .add("value", getValue()) // .toString(); // } // // @CheckReturnValue // public boolean isNull() { // return this instanceof JsonNull; // } // // @CheckReturnValue // public boolean isBoolean() { // return this instanceof JsonBoolean; // } // // @CheckReturnValue // public boolean isNumber() { // return this instanceof JsonNumber; // } // // @CheckReturnValue // public boolean isString() { // return this instanceof JsonString; // } // // @CheckReturnValue // public boolean isArray() { // return this instanceof JsonArray; // } // // @CheckReturnValue // public boolean isObject() { // return this instanceof JsonObject; // } // // @Nonnull // @CheckReturnValue // public JsonNull asNull() { // if (isNull()) { // return (JsonNull) this; // } // throw new IllegalStateException("This value is not a null"); // } // // @Nonnull // @CheckReturnValue // public JsonBoolean asBoolean() { // if (isBoolean()) { // return (JsonBoolean) this; // } // throw new IllegalStateException("This value is not a boolean"); // } // // @Nonnull // @CheckReturnValue // public JsonNumber asNumber() { // if (isNumber()) { // return (JsonNumber) this; // } // throw new IllegalStateException("This value is not a number"); // } // // @Nonnull // @CheckReturnValue // public JsonString asString() { // if (isString()) { // return (JsonString) this; // } // throw new IllegalStateException("This value is not a string"); // } // // @Nonnull // @CheckReturnValue // public JsonArray asArray() { // if (isArray()) { // return (JsonArray) this; // } // throw new IllegalStateException("This value is not an array"); // } // // @Nonnull // @CheckReturnValue // public JsonObject asObject() { // if (isObject()) { // return (JsonObject) this; // } // throw new IllegalStateException("This value is not an object"); // } // } // // Path: core/src/test/java/io/t28/json2java/core/Assertions.java // @Nonnull // @CheckReturnValue // public static JsonValueAssert assertThat(@Nullable JsonValue actual) { // return new JsonValueAssert(actual); // } // Path: core/src/test/java/io/t28/json2java/core/io/JsonParserImplTest.java import static io.t28.json2java.core.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.spy; import com.fasterxml.jackson.databind.ObjectMapper; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import io.t28.json2java.core.io.JsonParserImpl; import io.t28.json2java.core.io.exception.JsonParseException; import io.t28.json2java.core.json.JsonValue; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.util.Collections; import java.util.List; import java.util.Map; /* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.core.io; @SuppressWarnings("ResultOfMethodCallIgnored") public class JsonParserImplTest { private ObjectMapper mapper;
private JsonParserImpl underTest;
t28hub/json2java4idea
core/src/test/java/io/t28/json2java/core/io/JsonParserImplTest.java
// Path: core/src/main/java/io/t28/json2java/core/io/JsonParserImpl.java // public class JsonParserImpl implements JsonParser { // private final ObjectMapper mapper; // // public JsonParserImpl() { // this(new ObjectMapper()); // } // // @VisibleForTesting // JsonParserImpl(@Nonnull ObjectMapper mapper) { // this.mapper = mapper; // } // // @Nonnull // @Override // public JsonValue parse(@Nonnull String json) throws JsonParseException { // try { // final Object parsed = mapper.readValue(json, Object.class); // return JsonValue.wrap(parsed); // } catch (IOException e) { // throw new JsonParseException("Unable to parse a JSON string(" + json + ")", e); // } // } // } // // Path: core/src/main/java/io/t28/json2java/core/io/exception/JsonParseException.java // public class JsonParseException extends IOException { // private static final long serialVersionUID = 1477109671450199015L; // // public JsonParseException(@Nonnull String message, @Nonnull Throwable cause) { // super(message, cause); // } // } // // Path: core/src/main/java/io/t28/json2java/core/json/JsonValue.java // public abstract class JsonValue { // @Nonnull // @CheckReturnValue // public static JsonValue wrap(@Nullable Object value) { // return Stream.of(ValueType.values()) // .filter(type -> type.isAcceptable(value)) // .findFirst() // .orElseThrow(() -> new IllegalArgumentException("Unsupported type of value(" + value + ")")) // .wrap(value); // } // // @Nonnull // public abstract TypeName getType(); // // public abstract Object getValue(); // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("type", getType()) // .add("value", getValue()) // .toString(); // } // // @CheckReturnValue // public boolean isNull() { // return this instanceof JsonNull; // } // // @CheckReturnValue // public boolean isBoolean() { // return this instanceof JsonBoolean; // } // // @CheckReturnValue // public boolean isNumber() { // return this instanceof JsonNumber; // } // // @CheckReturnValue // public boolean isString() { // return this instanceof JsonString; // } // // @CheckReturnValue // public boolean isArray() { // return this instanceof JsonArray; // } // // @CheckReturnValue // public boolean isObject() { // return this instanceof JsonObject; // } // // @Nonnull // @CheckReturnValue // public JsonNull asNull() { // if (isNull()) { // return (JsonNull) this; // } // throw new IllegalStateException("This value is not a null"); // } // // @Nonnull // @CheckReturnValue // public JsonBoolean asBoolean() { // if (isBoolean()) { // return (JsonBoolean) this; // } // throw new IllegalStateException("This value is not a boolean"); // } // // @Nonnull // @CheckReturnValue // public JsonNumber asNumber() { // if (isNumber()) { // return (JsonNumber) this; // } // throw new IllegalStateException("This value is not a number"); // } // // @Nonnull // @CheckReturnValue // public JsonString asString() { // if (isString()) { // return (JsonString) this; // } // throw new IllegalStateException("This value is not a string"); // } // // @Nonnull // @CheckReturnValue // public JsonArray asArray() { // if (isArray()) { // return (JsonArray) this; // } // throw new IllegalStateException("This value is not an array"); // } // // @Nonnull // @CheckReturnValue // public JsonObject asObject() { // if (isObject()) { // return (JsonObject) this; // } // throw new IllegalStateException("This value is not an object"); // } // } // // Path: core/src/test/java/io/t28/json2java/core/Assertions.java // @Nonnull // @CheckReturnValue // public static JsonValueAssert assertThat(@Nullable JsonValue actual) { // return new JsonValueAssert(actual); // }
import static io.t28.json2java.core.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.spy; import com.fasterxml.jackson.databind.ObjectMapper; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import io.t28.json2java.core.io.JsonParserImpl; import io.t28.json2java.core.io.exception.JsonParseException; import io.t28.json2java.core.json.JsonValue; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.util.Collections; import java.util.List; import java.util.Map;
/* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.core.io; @SuppressWarnings("ResultOfMethodCallIgnored") public class JsonParserImplTest { private ObjectMapper mapper; private JsonParserImpl underTest; @Before public void setUp() throws Exception { mapper = spy(new ObjectMapper()); underTest = new JsonParserImpl(mapper); } @Test public void parseShouldReturnJsonNullWhenNull() throws Exception { // exercise
// Path: core/src/main/java/io/t28/json2java/core/io/JsonParserImpl.java // public class JsonParserImpl implements JsonParser { // private final ObjectMapper mapper; // // public JsonParserImpl() { // this(new ObjectMapper()); // } // // @VisibleForTesting // JsonParserImpl(@Nonnull ObjectMapper mapper) { // this.mapper = mapper; // } // // @Nonnull // @Override // public JsonValue parse(@Nonnull String json) throws JsonParseException { // try { // final Object parsed = mapper.readValue(json, Object.class); // return JsonValue.wrap(parsed); // } catch (IOException e) { // throw new JsonParseException("Unable to parse a JSON string(" + json + ")", e); // } // } // } // // Path: core/src/main/java/io/t28/json2java/core/io/exception/JsonParseException.java // public class JsonParseException extends IOException { // private static final long serialVersionUID = 1477109671450199015L; // // public JsonParseException(@Nonnull String message, @Nonnull Throwable cause) { // super(message, cause); // } // } // // Path: core/src/main/java/io/t28/json2java/core/json/JsonValue.java // public abstract class JsonValue { // @Nonnull // @CheckReturnValue // public static JsonValue wrap(@Nullable Object value) { // return Stream.of(ValueType.values()) // .filter(type -> type.isAcceptable(value)) // .findFirst() // .orElseThrow(() -> new IllegalArgumentException("Unsupported type of value(" + value + ")")) // .wrap(value); // } // // @Nonnull // public abstract TypeName getType(); // // public abstract Object getValue(); // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("type", getType()) // .add("value", getValue()) // .toString(); // } // // @CheckReturnValue // public boolean isNull() { // return this instanceof JsonNull; // } // // @CheckReturnValue // public boolean isBoolean() { // return this instanceof JsonBoolean; // } // // @CheckReturnValue // public boolean isNumber() { // return this instanceof JsonNumber; // } // // @CheckReturnValue // public boolean isString() { // return this instanceof JsonString; // } // // @CheckReturnValue // public boolean isArray() { // return this instanceof JsonArray; // } // // @CheckReturnValue // public boolean isObject() { // return this instanceof JsonObject; // } // // @Nonnull // @CheckReturnValue // public JsonNull asNull() { // if (isNull()) { // return (JsonNull) this; // } // throw new IllegalStateException("This value is not a null"); // } // // @Nonnull // @CheckReturnValue // public JsonBoolean asBoolean() { // if (isBoolean()) { // return (JsonBoolean) this; // } // throw new IllegalStateException("This value is not a boolean"); // } // // @Nonnull // @CheckReturnValue // public JsonNumber asNumber() { // if (isNumber()) { // return (JsonNumber) this; // } // throw new IllegalStateException("This value is not a number"); // } // // @Nonnull // @CheckReturnValue // public JsonString asString() { // if (isString()) { // return (JsonString) this; // } // throw new IllegalStateException("This value is not a string"); // } // // @Nonnull // @CheckReturnValue // public JsonArray asArray() { // if (isArray()) { // return (JsonArray) this; // } // throw new IllegalStateException("This value is not an array"); // } // // @Nonnull // @CheckReturnValue // public JsonObject asObject() { // if (isObject()) { // return (JsonObject) this; // } // throw new IllegalStateException("This value is not an object"); // } // } // // Path: core/src/test/java/io/t28/json2java/core/Assertions.java // @Nonnull // @CheckReturnValue // public static JsonValueAssert assertThat(@Nullable JsonValue actual) { // return new JsonValueAssert(actual); // } // Path: core/src/test/java/io/t28/json2java/core/io/JsonParserImplTest.java import static io.t28.json2java.core.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.spy; import com.fasterxml.jackson.databind.ObjectMapper; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import io.t28.json2java.core.io.JsonParserImpl; import io.t28.json2java.core.io.exception.JsonParseException; import io.t28.json2java.core.json.JsonValue; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.util.Collections; import java.util.List; import java.util.Map; /* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.core.io; @SuppressWarnings("ResultOfMethodCallIgnored") public class JsonParserImplTest { private ObjectMapper mapper; private JsonParserImpl underTest; @Before public void setUp() throws Exception { mapper = spy(new ObjectMapper()); underTest = new JsonParserImpl(mapper); } @Test public void parseShouldReturnJsonNullWhenNull() throws Exception { // exercise
final JsonValue value = underTest.parse("null");
t28hub/json2java4idea
core/src/test/java/io/t28/json2java/core/io/JsonParserImplTest.java
// Path: core/src/main/java/io/t28/json2java/core/io/JsonParserImpl.java // public class JsonParserImpl implements JsonParser { // private final ObjectMapper mapper; // // public JsonParserImpl() { // this(new ObjectMapper()); // } // // @VisibleForTesting // JsonParserImpl(@Nonnull ObjectMapper mapper) { // this.mapper = mapper; // } // // @Nonnull // @Override // public JsonValue parse(@Nonnull String json) throws JsonParseException { // try { // final Object parsed = mapper.readValue(json, Object.class); // return JsonValue.wrap(parsed); // } catch (IOException e) { // throw new JsonParseException("Unable to parse a JSON string(" + json + ")", e); // } // } // } // // Path: core/src/main/java/io/t28/json2java/core/io/exception/JsonParseException.java // public class JsonParseException extends IOException { // private static final long serialVersionUID = 1477109671450199015L; // // public JsonParseException(@Nonnull String message, @Nonnull Throwable cause) { // super(message, cause); // } // } // // Path: core/src/main/java/io/t28/json2java/core/json/JsonValue.java // public abstract class JsonValue { // @Nonnull // @CheckReturnValue // public static JsonValue wrap(@Nullable Object value) { // return Stream.of(ValueType.values()) // .filter(type -> type.isAcceptable(value)) // .findFirst() // .orElseThrow(() -> new IllegalArgumentException("Unsupported type of value(" + value + ")")) // .wrap(value); // } // // @Nonnull // public abstract TypeName getType(); // // public abstract Object getValue(); // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("type", getType()) // .add("value", getValue()) // .toString(); // } // // @CheckReturnValue // public boolean isNull() { // return this instanceof JsonNull; // } // // @CheckReturnValue // public boolean isBoolean() { // return this instanceof JsonBoolean; // } // // @CheckReturnValue // public boolean isNumber() { // return this instanceof JsonNumber; // } // // @CheckReturnValue // public boolean isString() { // return this instanceof JsonString; // } // // @CheckReturnValue // public boolean isArray() { // return this instanceof JsonArray; // } // // @CheckReturnValue // public boolean isObject() { // return this instanceof JsonObject; // } // // @Nonnull // @CheckReturnValue // public JsonNull asNull() { // if (isNull()) { // return (JsonNull) this; // } // throw new IllegalStateException("This value is not a null"); // } // // @Nonnull // @CheckReturnValue // public JsonBoolean asBoolean() { // if (isBoolean()) { // return (JsonBoolean) this; // } // throw new IllegalStateException("This value is not a boolean"); // } // // @Nonnull // @CheckReturnValue // public JsonNumber asNumber() { // if (isNumber()) { // return (JsonNumber) this; // } // throw new IllegalStateException("This value is not a number"); // } // // @Nonnull // @CheckReturnValue // public JsonString asString() { // if (isString()) { // return (JsonString) this; // } // throw new IllegalStateException("This value is not a string"); // } // // @Nonnull // @CheckReturnValue // public JsonArray asArray() { // if (isArray()) { // return (JsonArray) this; // } // throw new IllegalStateException("This value is not an array"); // } // // @Nonnull // @CheckReturnValue // public JsonObject asObject() { // if (isObject()) { // return (JsonObject) this; // } // throw new IllegalStateException("This value is not an object"); // } // } // // Path: core/src/test/java/io/t28/json2java/core/Assertions.java // @Nonnull // @CheckReturnValue // public static JsonValueAssert assertThat(@Nullable JsonValue actual) { // return new JsonValueAssert(actual); // }
import static io.t28.json2java.core.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.spy; import com.fasterxml.jackson.databind.ObjectMapper; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import io.t28.json2java.core.io.JsonParserImpl; import io.t28.json2java.core.io.exception.JsonParseException; import io.t28.json2java.core.json.JsonValue; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.util.Collections; import java.util.List; import java.util.Map;
@Test public void parseShouldReturnJsonArrayWhenArray() throws Exception { // exercise final JsonValue value = underTest.parse("[]"); // verify assertThat(value) .isJsonArray() .hasType(ParameterizedTypeName.get(List.class, Object.class)) .hasValue(Collections.emptyList()); } @Test public void parseShouldReturnJsonObjectWhenObject() throws Exception { // exercise final JsonValue value = underTest.parse("{}"); // verify assertThat(value) .isJsonObject() .hasType(ParameterizedTypeName.get(Map.class, String.class, Object.class)) .hasValue(Collections.emptyMap()); } @Test public void parseShouldThrowExceptionWhenInvalidJson() throws Exception { // verify assertThatThrownBy(() -> { // exercise underTest.parse("{{invalid json}}");
// Path: core/src/main/java/io/t28/json2java/core/io/JsonParserImpl.java // public class JsonParserImpl implements JsonParser { // private final ObjectMapper mapper; // // public JsonParserImpl() { // this(new ObjectMapper()); // } // // @VisibleForTesting // JsonParserImpl(@Nonnull ObjectMapper mapper) { // this.mapper = mapper; // } // // @Nonnull // @Override // public JsonValue parse(@Nonnull String json) throws JsonParseException { // try { // final Object parsed = mapper.readValue(json, Object.class); // return JsonValue.wrap(parsed); // } catch (IOException e) { // throw new JsonParseException("Unable to parse a JSON string(" + json + ")", e); // } // } // } // // Path: core/src/main/java/io/t28/json2java/core/io/exception/JsonParseException.java // public class JsonParseException extends IOException { // private static final long serialVersionUID = 1477109671450199015L; // // public JsonParseException(@Nonnull String message, @Nonnull Throwable cause) { // super(message, cause); // } // } // // Path: core/src/main/java/io/t28/json2java/core/json/JsonValue.java // public abstract class JsonValue { // @Nonnull // @CheckReturnValue // public static JsonValue wrap(@Nullable Object value) { // return Stream.of(ValueType.values()) // .filter(type -> type.isAcceptable(value)) // .findFirst() // .orElseThrow(() -> new IllegalArgumentException("Unsupported type of value(" + value + ")")) // .wrap(value); // } // // @Nonnull // public abstract TypeName getType(); // // public abstract Object getValue(); // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("type", getType()) // .add("value", getValue()) // .toString(); // } // // @CheckReturnValue // public boolean isNull() { // return this instanceof JsonNull; // } // // @CheckReturnValue // public boolean isBoolean() { // return this instanceof JsonBoolean; // } // // @CheckReturnValue // public boolean isNumber() { // return this instanceof JsonNumber; // } // // @CheckReturnValue // public boolean isString() { // return this instanceof JsonString; // } // // @CheckReturnValue // public boolean isArray() { // return this instanceof JsonArray; // } // // @CheckReturnValue // public boolean isObject() { // return this instanceof JsonObject; // } // // @Nonnull // @CheckReturnValue // public JsonNull asNull() { // if (isNull()) { // return (JsonNull) this; // } // throw new IllegalStateException("This value is not a null"); // } // // @Nonnull // @CheckReturnValue // public JsonBoolean asBoolean() { // if (isBoolean()) { // return (JsonBoolean) this; // } // throw new IllegalStateException("This value is not a boolean"); // } // // @Nonnull // @CheckReturnValue // public JsonNumber asNumber() { // if (isNumber()) { // return (JsonNumber) this; // } // throw new IllegalStateException("This value is not a number"); // } // // @Nonnull // @CheckReturnValue // public JsonString asString() { // if (isString()) { // return (JsonString) this; // } // throw new IllegalStateException("This value is not a string"); // } // // @Nonnull // @CheckReturnValue // public JsonArray asArray() { // if (isArray()) { // return (JsonArray) this; // } // throw new IllegalStateException("This value is not an array"); // } // // @Nonnull // @CheckReturnValue // public JsonObject asObject() { // if (isObject()) { // return (JsonObject) this; // } // throw new IllegalStateException("This value is not an object"); // } // } // // Path: core/src/test/java/io/t28/json2java/core/Assertions.java // @Nonnull // @CheckReturnValue // public static JsonValueAssert assertThat(@Nullable JsonValue actual) { // return new JsonValueAssert(actual); // } // Path: core/src/test/java/io/t28/json2java/core/io/JsonParserImplTest.java import static io.t28.json2java.core.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.spy; import com.fasterxml.jackson.databind.ObjectMapper; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import io.t28.json2java.core.io.JsonParserImpl; import io.t28.json2java.core.io.exception.JsonParseException; import io.t28.json2java.core.json.JsonValue; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.util.Collections; import java.util.List; import java.util.Map; @Test public void parseShouldReturnJsonArrayWhenArray() throws Exception { // exercise final JsonValue value = underTest.parse("[]"); // verify assertThat(value) .isJsonArray() .hasType(ParameterizedTypeName.get(List.class, Object.class)) .hasValue(Collections.emptyList()); } @Test public void parseShouldReturnJsonObjectWhenObject() throws Exception { // exercise final JsonValue value = underTest.parse("{}"); // verify assertThat(value) .isJsonObject() .hasType(ParameterizedTypeName.get(Map.class, String.class, Object.class)) .hasValue(Collections.emptyMap()); } @Test public void parseShouldThrowExceptionWhenInvalidJson() throws Exception { // verify assertThatThrownBy(() -> { // exercise underTest.parse("{{invalid json}}");
}).isInstanceOf(JsonParseException.class);
t28hub/json2java4idea
idea/src/test/java/io/t28/json2java/idea/Assertions.java
// Path: idea/src/test/java/org/jdom/ElementAssert.java // public class ElementAssert extends AbstractAssert<ElementAssert, Element> { // public ElementAssert(@Nullable Element actual) { // super(actual, ElementAssert.class); // } // // @Nonnull // public ElementAssert hasName(@Nonnull String expected) { // isNotNull(); // // final String actual = this.actual.getName(); // Assertions.assertThat(actual) // .overridingErrorMessage("Expected root element to be named <%s> but was <%s>", expected, actual) // .isEqualTo(expected); // // return this; // } // // @Nonnull // public ElementAssert hasAttribute(@Nonnull String expectedName, @Nonnull String expectedValue) { // isNotNull(); // // final Attribute actual = this.actual.getAttribute(expectedName); // Assertions.assertThat(actual) // .overridingErrorMessage("Expected attribute named <%s> does not exist", expectedName) // .isNotNull(); // // final String actualName = actual.getName(); // Assertions.assertThat(actualName) // .overridingErrorMessage("Expected attribute name to be <%s> but was <%s>", expectedName, actualName) // .isEqualTo(expectedName); // // final String actualValue = actual.getValue(); // Assertions.assertThat(actualValue) // .overridingErrorMessage("Expected attribute value to be <%s> but was <%s>", expectedValue, actualValue) // .isEqualTo(expectedValue); // // return this; // } // }
import org.jdom.Element; import org.jdom.ElementAssert; import javax.annotation.CheckReturnValue; import javax.annotation.Nonnull; import javax.annotation.Nullable;
/* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.idea; public class Assertions { private Assertions() { } @Nonnull @CheckReturnValue
// Path: idea/src/test/java/org/jdom/ElementAssert.java // public class ElementAssert extends AbstractAssert<ElementAssert, Element> { // public ElementAssert(@Nullable Element actual) { // super(actual, ElementAssert.class); // } // // @Nonnull // public ElementAssert hasName(@Nonnull String expected) { // isNotNull(); // // final String actual = this.actual.getName(); // Assertions.assertThat(actual) // .overridingErrorMessage("Expected root element to be named <%s> but was <%s>", expected, actual) // .isEqualTo(expected); // // return this; // } // // @Nonnull // public ElementAssert hasAttribute(@Nonnull String expectedName, @Nonnull String expectedValue) { // isNotNull(); // // final Attribute actual = this.actual.getAttribute(expectedName); // Assertions.assertThat(actual) // .overridingErrorMessage("Expected attribute named <%s> does not exist", expectedName) // .isNotNull(); // // final String actualName = actual.getName(); // Assertions.assertThat(actualName) // .overridingErrorMessage("Expected attribute name to be <%s> but was <%s>", expectedName, actualName) // .isEqualTo(expectedName); // // final String actualValue = actual.getValue(); // Assertions.assertThat(actualValue) // .overridingErrorMessage("Expected attribute value to be <%s> but was <%s>", expectedValue, actualValue) // .isEqualTo(expectedValue); // // return this; // } // } // Path: idea/src/test/java/io/t28/json2java/idea/Assertions.java import org.jdom.Element; import org.jdom.ElementAssert; import javax.annotation.CheckReturnValue; import javax.annotation.Nonnull; import javax.annotation.Nullable; /* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.idea; public class Assertions { private Assertions() { } @Nonnull @CheckReturnValue
public static ElementAssert assertThat(@Nullable Element actual) {
t28hub/json2java4idea
idea/src/test/java/io/t28/json2java/idea/naming/MethodNamePolicyTest.java
// Path: idea/src/test/java/io/t28/json2java/idea/IdeaProjectTest.java // public class IdeaProjectTest { // private JavaCodeInsightTestFixture fixture; // // @Before // public void setUp() throws Exception { // final IdeaTestFixtureFactory ideaFixtureFactory = IdeaTestFixtureFactory.getFixtureFactory(); // final JavaTestFixtureFactory javaFixtureFactory = JavaTestFixtureFactory.getFixtureFactory(); // final TestFixtureBuilder<IdeaProjectTestFixture> fixtureBuilder = ideaFixtureFactory.createLightFixtureBuilder(); // fixture = javaFixtureFactory.createCodeInsightFixture(fixtureBuilder.getFixture()); // fixture.setUp(); // } // // @After // public void tearDown() throws Exception { // fixture.tearDown(); // } // // @Nonnull // @CheckReturnValue // protected Application getApplication() { // if (fixture == null) { // throw new AssertionError("getApplication() must call after setUp()"); // } // return ApplicationManager.getApplication(); // } // // @Nonnull // @CheckReturnValue // protected Project getProject() { // if (fixture == null) { // throw new AssertionError("getProject() must call after setUp()"); // } // return fixture.getProject(); // } // } // // Path: idea/src/main/java/io/t28/json2java/idea/util/PsiTypeConverter.java // public class PsiTypeConverter implements Function<TypeName, PsiType> { // private final PsiManager psiManager; // // @Inject // public PsiTypeConverter(@Nonnull PsiManager psiManager) { // this.psiManager = psiManager; // } // // @Nonnull // @CheckReturnValue // @Override // public PsiType apply(@Nonnull TypeName typeName) { // return Stream.of(PrimitiveType.values()) // .filter(primitiveType -> primitiveType.isSameAs(typeName)) // .map(PrimitiveType::psiType) // .findFirst() // .orElseGet(() -> PsiType.getJavaLangObject(psiManager, GlobalSearchScope.EMPTY_SCOPE)); // } // // @Nonnull // @CheckReturnValue // static TypeName box(@Nonnull TypeName typeName) { // try { // return typeName.box(); // } catch (Exception e) { // return typeName; // } // } // // @Nonnull // @CheckReturnValue // static TypeName unbox(@Nonnull TypeName typeName) { // try { // return typeName.unbox(); // } catch (Exception e) { // return typeName; // } // } // // @SuppressWarnings("unused") // enum PrimitiveType { // BOOLEAN(PsiType.BOOLEAN, TypeName.BOOLEAN), // BYTE(PsiType.BYTE, TypeName.BYTE), // CHAR(PsiType.CHAR, TypeName.CHAR), // DOUBLE(PsiType.DOUBLE, TypeName.DOUBLE), // FLOAT(PsiType.FLOAT, TypeName.FLOAT), // INT(PsiType.INT, TypeName.INT), // LONG(PsiType.LONG, TypeName.LONG), // SHORT(PsiType.SHORT, TypeName.SHORT), // VOID(PsiType.VOID, TypeName.VOID); // // private final PsiType psiType; // private final TypeName typeName; // // PrimitiveType(@Nonnull PsiType psiType, @Nonnull TypeName typeName) { // this.psiType = psiType; // this.typeName = typeName; // } // // @Nonnull // @CheckReturnValue // PsiType psiType() { // return psiType; // } // // @CheckReturnValue // boolean isSameAs(@Nonnull TypeName typeName) { // final TypeName boxTypeName = box(typeName); // final TypeName unboxTypeName = unbox(typeName); // return this.typeName.equals(boxTypeName) || this.typeName.equals(unboxTypeName); // } // } // }
import com.intellij.openapi.application.Application; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiManager; import com.squareup.javapoet.TypeName; import io.t28.json2java.idea.IdeaProjectTest; import io.t28.json2java.idea.util.PsiTypeConverter; import org.junit.Before; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy;
/* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.idea.naming; public class MethodNamePolicyTest extends IdeaProjectTest { private Application application; private MethodNamePolicy underTest; @Before @Override public void setUp() throws Exception { super.setUp(); application = getApplication(); final Project project = getProject(); final PsiManager psiManager = PsiManager.getInstance(project);
// Path: idea/src/test/java/io/t28/json2java/idea/IdeaProjectTest.java // public class IdeaProjectTest { // private JavaCodeInsightTestFixture fixture; // // @Before // public void setUp() throws Exception { // final IdeaTestFixtureFactory ideaFixtureFactory = IdeaTestFixtureFactory.getFixtureFactory(); // final JavaTestFixtureFactory javaFixtureFactory = JavaTestFixtureFactory.getFixtureFactory(); // final TestFixtureBuilder<IdeaProjectTestFixture> fixtureBuilder = ideaFixtureFactory.createLightFixtureBuilder(); // fixture = javaFixtureFactory.createCodeInsightFixture(fixtureBuilder.getFixture()); // fixture.setUp(); // } // // @After // public void tearDown() throws Exception { // fixture.tearDown(); // } // // @Nonnull // @CheckReturnValue // protected Application getApplication() { // if (fixture == null) { // throw new AssertionError("getApplication() must call after setUp()"); // } // return ApplicationManager.getApplication(); // } // // @Nonnull // @CheckReturnValue // protected Project getProject() { // if (fixture == null) { // throw new AssertionError("getProject() must call after setUp()"); // } // return fixture.getProject(); // } // } // // Path: idea/src/main/java/io/t28/json2java/idea/util/PsiTypeConverter.java // public class PsiTypeConverter implements Function<TypeName, PsiType> { // private final PsiManager psiManager; // // @Inject // public PsiTypeConverter(@Nonnull PsiManager psiManager) { // this.psiManager = psiManager; // } // // @Nonnull // @CheckReturnValue // @Override // public PsiType apply(@Nonnull TypeName typeName) { // return Stream.of(PrimitiveType.values()) // .filter(primitiveType -> primitiveType.isSameAs(typeName)) // .map(PrimitiveType::psiType) // .findFirst() // .orElseGet(() -> PsiType.getJavaLangObject(psiManager, GlobalSearchScope.EMPTY_SCOPE)); // } // // @Nonnull // @CheckReturnValue // static TypeName box(@Nonnull TypeName typeName) { // try { // return typeName.box(); // } catch (Exception e) { // return typeName; // } // } // // @Nonnull // @CheckReturnValue // static TypeName unbox(@Nonnull TypeName typeName) { // try { // return typeName.unbox(); // } catch (Exception e) { // return typeName; // } // } // // @SuppressWarnings("unused") // enum PrimitiveType { // BOOLEAN(PsiType.BOOLEAN, TypeName.BOOLEAN), // BYTE(PsiType.BYTE, TypeName.BYTE), // CHAR(PsiType.CHAR, TypeName.CHAR), // DOUBLE(PsiType.DOUBLE, TypeName.DOUBLE), // FLOAT(PsiType.FLOAT, TypeName.FLOAT), // INT(PsiType.INT, TypeName.INT), // LONG(PsiType.LONG, TypeName.LONG), // SHORT(PsiType.SHORT, TypeName.SHORT), // VOID(PsiType.VOID, TypeName.VOID); // // private final PsiType psiType; // private final TypeName typeName; // // PrimitiveType(@Nonnull PsiType psiType, @Nonnull TypeName typeName) { // this.psiType = psiType; // this.typeName = typeName; // } // // @Nonnull // @CheckReturnValue // PsiType psiType() { // return psiType; // } // // @CheckReturnValue // boolean isSameAs(@Nonnull TypeName typeName) { // final TypeName boxTypeName = box(typeName); // final TypeName unboxTypeName = unbox(typeName); // return this.typeName.equals(boxTypeName) || this.typeName.equals(unboxTypeName); // } // } // } // Path: idea/src/test/java/io/t28/json2java/idea/naming/MethodNamePolicyTest.java import com.intellij.openapi.application.Application; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiManager; import com.squareup.javapoet.TypeName; import io.t28.json2java.idea.IdeaProjectTest; import io.t28.json2java.idea.util.PsiTypeConverter; import org.junit.Before; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; /* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.idea.naming; public class MethodNamePolicyTest extends IdeaProjectTest { private Application application; private MethodNamePolicy underTest; @Before @Override public void setUp() throws Exception { super.setUp(); application = getApplication(); final Project project = getProject(); final PsiManager psiManager = PsiManager.getInstance(project);
final PsiTypeConverter converter = new PsiTypeConverter(psiManager);
t28hub/json2java4idea
idea/src/main/java/io/t28/json2java/idea/setting/PersistentJson2JavaSettings.java
// Path: core/src/main/java/io/t28/json2java/core/Style.java // public enum Style { // NONE { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new ModelClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }, // GSON { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new GsonClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }, // JACKSON { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new JacksonClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }, // MOSHI { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new MoshiClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }; // // @Nonnull // @CheckReturnValue // abstract ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy); // // @Nonnull // @CheckReturnValue // public static Optional<Style> fromName(@Nonnull String name) { // return Stream.of(Style.values()) // .filter(style -> style.name().equalsIgnoreCase(name)) // .findFirst(); // } // // @Nonnull // @CheckReturnValue // public static Style fromName(@Nonnull String name, @Nonnull Style defaultStyle) { // return fromName(name).orElse(defaultStyle); // } // // public String get() { // return ""; // } // }
import com.intellij.openapi.components.PersistentStateComponent; import com.intellij.openapi.components.State; import com.intellij.openapi.components.Storage; import io.t28.json2java.core.Style; import org.jdom.Element; import org.jetbrains.annotations.Nullable; import javax.annotation.CheckReturnValue; import javax.annotation.Nonnull;
/* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.idea.setting; @State( name = "Json2JavaSettings", storages = @Storage(value = "$PROJECT_CONFIG_DIR$/json2java.xml") ) public class PersistentJson2JavaSettings implements Json2JavaSettings, PersistentStateComponent<Element> { private static final String NO_TEXT = ""; private static final String ENABLED = "true"; private static final String ROOT_ELEMENT = "component"; private static final String CLASS_STYLE_ATTRIBUTE = "style"; private static final String CLASS_NAME_PREFIX_ATTRIBUTE = "classNamePrefix"; private static final String CLASS_NAME_SUFFIX_ATTRIBUTE = "classNameSuffix"; private static final String ANNOTATION_GENERATED_ENABLED = "annotationGenerated"; private static final String ANNOTATION_SUPPRESS_WARNINGS_ENABLED = "annotationSuppressWarnings";
// Path: core/src/main/java/io/t28/json2java/core/Style.java // public enum Style { // NONE { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new ModelClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }, // GSON { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new GsonClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }, // JACKSON { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new JacksonClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }, // MOSHI { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new MoshiClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }; // // @Nonnull // @CheckReturnValue // abstract ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy); // // @Nonnull // @CheckReturnValue // public static Optional<Style> fromName(@Nonnull String name) { // return Stream.of(Style.values()) // .filter(style -> style.name().equalsIgnoreCase(name)) // .findFirst(); // } // // @Nonnull // @CheckReturnValue // public static Style fromName(@Nonnull String name, @Nonnull Style defaultStyle) { // return fromName(name).orElse(defaultStyle); // } // // public String get() { // return ""; // } // } // Path: idea/src/main/java/io/t28/json2java/idea/setting/PersistentJson2JavaSettings.java import com.intellij.openapi.components.PersistentStateComponent; import com.intellij.openapi.components.State; import com.intellij.openapi.components.Storage; import io.t28.json2java.core.Style; import org.jdom.Element; import org.jetbrains.annotations.Nullable; import javax.annotation.CheckReturnValue; import javax.annotation.Nonnull; /* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.idea.setting; @State( name = "Json2JavaSettings", storages = @Storage(value = "$PROJECT_CONFIG_DIR$/json2java.xml") ) public class PersistentJson2JavaSettings implements Json2JavaSettings, PersistentStateComponent<Element> { private static final String NO_TEXT = ""; private static final String ENABLED = "true"; private static final String ROOT_ELEMENT = "component"; private static final String CLASS_STYLE_ATTRIBUTE = "style"; private static final String CLASS_NAME_PREFIX_ATTRIBUTE = "classNamePrefix"; private static final String CLASS_NAME_SUFFIX_ATTRIBUTE = "classNameSuffix"; private static final String ANNOTATION_GENERATED_ENABLED = "annotationGenerated"; private static final String ANNOTATION_SUPPRESS_WARNINGS_ENABLED = "annotationSuppressWarnings";
private Style style;
t28hub/json2java4idea
core/src/test/java/io/t28/json2java/core/annotation/GeneratedAnnotationPolicyTest.java
// Path: core/src/test/java/io/t28/json2java/core/Assertions.java // @Nonnull // @CheckReturnValue // public static JsonValueAssert assertThat(@Nullable JsonValue actual) { // return new JsonValueAssert(actual); // }
import com.squareup.javapoet.AnnotationSpec; import com.squareup.javapoet.TypeSpec; import org.junit.Before; import org.junit.Test; import javax.annotation.Generated; import static io.t28.json2java.core.Assertions.assertThat;
/* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.core.annotation; public class GeneratedAnnotationPolicyTest { private GeneratedAnnotationPolicy underTest; @Before public void setUp() throws Exception { underTest = new GeneratedAnnotationPolicy(this.getClass()); } @Test public void applyShouldAddGeneratedAnnotation() throws Exception { // setup final TypeSpec.Builder builder = TypeSpec.classBuilder("Test"); // exercise underTest.apply(builder); // verify
// Path: core/src/test/java/io/t28/json2java/core/Assertions.java // @Nonnull // @CheckReturnValue // public static JsonValueAssert assertThat(@Nullable JsonValue actual) { // return new JsonValueAssert(actual); // } // Path: core/src/test/java/io/t28/json2java/core/annotation/GeneratedAnnotationPolicyTest.java import com.squareup.javapoet.AnnotationSpec; import com.squareup.javapoet.TypeSpec; import org.junit.Before; import org.junit.Test; import javax.annotation.Generated; import static io.t28.json2java.core.Assertions.assertThat; /* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.core.annotation; public class GeneratedAnnotationPolicyTest { private GeneratedAnnotationPolicy underTest; @Before public void setUp() throws Exception { underTest = new GeneratedAnnotationPolicy(this.getClass()); } @Test public void applyShouldAddGeneratedAnnotation() throws Exception { // setup final TypeSpec.Builder builder = TypeSpec.classBuilder("Test"); // exercise underTest.apply(builder); // verify
assertThat(builder.build())
t28hub/json2java4idea
core/src/main/java/io/t28/json2java/core/io/JavaBuilder.java
// Path: core/src/main/java/io/t28/json2java/core/io/exception/JavaBuildException.java // public class JavaBuildException extends IOException { // private static final long serialVersionUID = 5642915429649238000L; // // public JavaBuildException(@Nonnull String message, @Nonnull Throwable cause) { // super(message, cause); // } // }
import com.squareup.javapoet.TypeSpec; import io.t28.json2java.core.io.exception.JavaBuildException; import javax.annotation.CheckReturnValue; import javax.annotation.Nonnull;
/* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.core.io; public interface JavaBuilder { @Nonnull @CheckReturnValue
// Path: core/src/main/java/io/t28/json2java/core/io/exception/JavaBuildException.java // public class JavaBuildException extends IOException { // private static final long serialVersionUID = 5642915429649238000L; // // public JavaBuildException(@Nonnull String message, @Nonnull Throwable cause) { // super(message, cause); // } // } // Path: core/src/main/java/io/t28/json2java/core/io/JavaBuilder.java import com.squareup.javapoet.TypeSpec; import io.t28.json2java.core.io.exception.JavaBuildException; import javax.annotation.CheckReturnValue; import javax.annotation.Nonnull; /* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.core.io; public interface JavaBuilder { @Nonnull @CheckReturnValue
String build(@Nonnull String packageName, @Nonnull TypeSpec typeSpec) throws JavaBuildException;
t28hub/json2java4idea
idea/src/main/java/io/t28/json2java/idea/naming/FieldNamePolicy.java
// Path: core/src/main/java/io/t28/json2java/core/naming/DefaultNamePolicy.java // public enum DefaultNamePolicy implements NamePolicy { // CLASS { // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // return format(name, CaseFormat.UPPER_CAMEL); // } // }, // METHOD { // private static final String BOOLEAN_PREFIX = "is"; // private static final String GENERAL_PREFIX = "get"; // // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // final StringBuilder builder = new StringBuilder(); // if (type.equals(TypeName.BOOLEAN) || type.equals(ClassName.get(Boolean.class))) { // builder.append(BOOLEAN_PREFIX); // } else { // builder.append(GENERAL_PREFIX); // } // return builder.append(format(name, CaseFormat.UPPER_CAMEL)) // .toString(); // } // }, // FIELD { // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // return format(name, CaseFormat.LOWER_CAMEL); // } // }, // PARAMETER { // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // return format(name, CaseFormat.LOWER_CAMEL); // } // }; // // private static final String NO_TEXT = ""; // private static final String DELIMITER = "_"; // private static final String DELIMITER_REGEX = "(_|-|\\s|\\.|:)"; // private static final String CAMEL_CASE_REGEX = "(?<!(^|[A-Z]))(?=[A-Z])|(?<!^)(?=[A-Z][a-z])"; // private static final String INVALID_IDENTIFIER_REGEX = "[^A-Za-z0-9_$]"; // // @Nonnull // @CheckReturnValue // public static String format(@Nonnull String name, @Nonnull CaseFormat format) { // final Matcher matcher = Pattern.compile(DELIMITER_REGEX).matcher(name); // final String pattern; // if (matcher.find()) { // pattern = DELIMITER_REGEX; // } else { // pattern = CAMEL_CASE_REGEX; // } // final String snakeCase = Stream.of(name.split(pattern)) // .map(Ascii::toLowerCase) // .map(part -> part.replaceAll(INVALID_IDENTIFIER_REGEX, NO_TEXT)) // .filter(part -> !Strings.isNullOrEmpty(part)) // .collect(Collectors.joining(DELIMITER)); // return CaseFormat.LOWER_UNDERSCORE.to(format, snakeCase); // } // } // // Path: core/src/main/java/io/t28/json2java/core/naming/NamePolicy.java // public interface NamePolicy { // @Nonnull // @CheckReturnValue // String convert(@Nonnull String name, @Nonnull TypeName type); // }
import com.google.common.base.CaseFormat; import com.google.common.base.Strings; import com.google.inject.Inject; import com.intellij.psi.codeStyle.JavaCodeStyleManager; import com.intellij.psi.codeStyle.VariableKind; import com.squareup.javapoet.TypeName; import io.t28.json2java.core.naming.DefaultNamePolicy; import io.t28.json2java.core.naming.NamePolicy; import javax.annotation.Nonnull;
/* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.idea.naming; public class FieldNamePolicy implements NamePolicy { private final JavaCodeStyleManager codeStyleManager; @Inject public FieldNamePolicy(@Nonnull JavaCodeStyleManager codeStyleManager) { this.codeStyleManager = codeStyleManager; } @Nonnull @Override public String convert(@Nonnull String name, @Nonnull TypeName type) {
// Path: core/src/main/java/io/t28/json2java/core/naming/DefaultNamePolicy.java // public enum DefaultNamePolicy implements NamePolicy { // CLASS { // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // return format(name, CaseFormat.UPPER_CAMEL); // } // }, // METHOD { // private static final String BOOLEAN_PREFIX = "is"; // private static final String GENERAL_PREFIX = "get"; // // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // final StringBuilder builder = new StringBuilder(); // if (type.equals(TypeName.BOOLEAN) || type.equals(ClassName.get(Boolean.class))) { // builder.append(BOOLEAN_PREFIX); // } else { // builder.append(GENERAL_PREFIX); // } // return builder.append(format(name, CaseFormat.UPPER_CAMEL)) // .toString(); // } // }, // FIELD { // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // return format(name, CaseFormat.LOWER_CAMEL); // } // }, // PARAMETER { // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // return format(name, CaseFormat.LOWER_CAMEL); // } // }; // // private static final String NO_TEXT = ""; // private static final String DELIMITER = "_"; // private static final String DELIMITER_REGEX = "(_|-|\\s|\\.|:)"; // private static final String CAMEL_CASE_REGEX = "(?<!(^|[A-Z]))(?=[A-Z])|(?<!^)(?=[A-Z][a-z])"; // private static final String INVALID_IDENTIFIER_REGEX = "[^A-Za-z0-9_$]"; // // @Nonnull // @CheckReturnValue // public static String format(@Nonnull String name, @Nonnull CaseFormat format) { // final Matcher matcher = Pattern.compile(DELIMITER_REGEX).matcher(name); // final String pattern; // if (matcher.find()) { // pattern = DELIMITER_REGEX; // } else { // pattern = CAMEL_CASE_REGEX; // } // final String snakeCase = Stream.of(name.split(pattern)) // .map(Ascii::toLowerCase) // .map(part -> part.replaceAll(INVALID_IDENTIFIER_REGEX, NO_TEXT)) // .filter(part -> !Strings.isNullOrEmpty(part)) // .collect(Collectors.joining(DELIMITER)); // return CaseFormat.LOWER_UNDERSCORE.to(format, snakeCase); // } // } // // Path: core/src/main/java/io/t28/json2java/core/naming/NamePolicy.java // public interface NamePolicy { // @Nonnull // @CheckReturnValue // String convert(@Nonnull String name, @Nonnull TypeName type); // } // Path: idea/src/main/java/io/t28/json2java/idea/naming/FieldNamePolicy.java import com.google.common.base.CaseFormat; import com.google.common.base.Strings; import com.google.inject.Inject; import com.intellij.psi.codeStyle.JavaCodeStyleManager; import com.intellij.psi.codeStyle.VariableKind; import com.squareup.javapoet.TypeName; import io.t28.json2java.core.naming.DefaultNamePolicy; import io.t28.json2java.core.naming.NamePolicy; import javax.annotation.Nonnull; /* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.idea.naming; public class FieldNamePolicy implements NamePolicy { private final JavaCodeStyleManager codeStyleManager; @Inject public FieldNamePolicy(@Nonnull JavaCodeStyleManager codeStyleManager) { this.codeStyleManager = codeStyleManager; } @Nonnull @Override public String convert(@Nonnull String name, @Nonnull TypeName type) {
final String propertyName = DefaultNamePolicy.format(name, CaseFormat.LOWER_CAMEL);
t28hub/json2java4idea
idea/src/test/java/io/t28/json2java/idea/setting/TemporaryJson2JavaSettingsTest.java
// Path: core/src/main/java/io/t28/json2java/core/Style.java // public enum Style { // NONE { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new ModelClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }, // GSON { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new GsonClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }, // JACKSON { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new JacksonClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }, // MOSHI { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new MoshiClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }; // // @Nonnull // @CheckReturnValue // abstract ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy); // // @Nonnull // @CheckReturnValue // public static Optional<Style> fromName(@Nonnull String name) { // return Stream.of(Style.values()) // .filter(style -> style.name().equalsIgnoreCase(name)) // .findFirst(); // } // // @Nonnull // @CheckReturnValue // public static Style fromName(@Nonnull String name, @Nonnull Style defaultStyle) { // return fromName(name).orElse(defaultStyle); // } // // public String get() { // return ""; // } // }
import io.t28.json2java.core.Style; import org.junit.Before; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat;
/* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.idea.setting; public class TemporaryJson2JavaSettingsTest { private TemporaryJson2JavaSettings underTest; @Before public void setUp() throws Exception { underTest = new TemporaryJson2JavaSettings(); } @Test public void getStyleShouldReturnStyle() throws Exception { // setup
// Path: core/src/main/java/io/t28/json2java/core/Style.java // public enum Style { // NONE { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new ModelClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }, // GSON { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new GsonClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }, // JACKSON { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new JacksonClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }, // MOSHI { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new MoshiClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }; // // @Nonnull // @CheckReturnValue // abstract ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy); // // @Nonnull // @CheckReturnValue // public static Optional<Style> fromName(@Nonnull String name) { // return Stream.of(Style.values()) // .filter(style -> style.name().equalsIgnoreCase(name)) // .findFirst(); // } // // @Nonnull // @CheckReturnValue // public static Style fromName(@Nonnull String name, @Nonnull Style defaultStyle) { // return fromName(name).orElse(defaultStyle); // } // // public String get() { // return ""; // } // } // Path: idea/src/test/java/io/t28/json2java/idea/setting/TemporaryJson2JavaSettingsTest.java import io.t28.json2java.core.Style; import org.junit.Before; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; /* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.idea.setting; public class TemporaryJson2JavaSettingsTest { private TemporaryJson2JavaSettings underTest; @Before public void setUp() throws Exception { underTest = new TemporaryJson2JavaSettings(); } @Test public void getStyleShouldReturnStyle() throws Exception { // setup
underTest.setStyle(Style.GSON)
t28hub/json2java4idea
idea/src/test/java/io/t28/json2java/idea/validator/ClassSuffixValidatorTest.java
// Path: idea/src/test/java/io/t28/json2java/idea/IdeaProjectTest.java // public class IdeaProjectTest { // private JavaCodeInsightTestFixture fixture; // // @Before // public void setUp() throws Exception { // final IdeaTestFixtureFactory ideaFixtureFactory = IdeaTestFixtureFactory.getFixtureFactory(); // final JavaTestFixtureFactory javaFixtureFactory = JavaTestFixtureFactory.getFixtureFactory(); // final TestFixtureBuilder<IdeaProjectTestFixture> fixtureBuilder = ideaFixtureFactory.createLightFixtureBuilder(); // fixture = javaFixtureFactory.createCodeInsightFixture(fixtureBuilder.getFixture()); // fixture.setUp(); // } // // @After // public void tearDown() throws Exception { // fixture.tearDown(); // } // // @Nonnull // @CheckReturnValue // protected Application getApplication() { // if (fixture == null) { // throw new AssertionError("getApplication() must call after setUp()"); // } // return ApplicationManager.getApplication(); // } // // @Nonnull // @CheckReturnValue // protected Project getProject() { // if (fixture == null) { // throw new AssertionError("getProject() must call after setUp()"); // } // return fixture.getProject(); // } // } // // Path: idea/src/main/java/io/t28/json2java/idea/Json2JavaBundle.java // public class Json2JavaBundle extends AbstractBundle { // private static final String BUNDLE = "messages.Json2Java4IdeaBundle"; // // public Json2JavaBundle() { // super(BUNDLE); // } // // @Nonnull // public static Json2JavaBundle getInstance() { // return new Json2JavaBundle(); // } // // @Nonnull // @CheckReturnValue // public String message(@Nonnull @PropertyKey(resourceBundle = BUNDLE) String key, @Nonnull Object... objects) { // return getMessage(key, objects); // } // }
import com.intellij.openapi.project.Project; import com.intellij.psi.PsiNameHelper; import io.t28.json2java.idea.IdeaProjectTest; import io.t28.json2java.idea.Json2JavaBundle; import org.junit.Before; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat;
/* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.idea.validator; public class ClassSuffixValidatorTest extends IdeaProjectTest { private ClassSuffixValidator underTest; @Before @Override public void setUp() throws Exception { super.setUp(); final Project project = getProject();
// Path: idea/src/test/java/io/t28/json2java/idea/IdeaProjectTest.java // public class IdeaProjectTest { // private JavaCodeInsightTestFixture fixture; // // @Before // public void setUp() throws Exception { // final IdeaTestFixtureFactory ideaFixtureFactory = IdeaTestFixtureFactory.getFixtureFactory(); // final JavaTestFixtureFactory javaFixtureFactory = JavaTestFixtureFactory.getFixtureFactory(); // final TestFixtureBuilder<IdeaProjectTestFixture> fixtureBuilder = ideaFixtureFactory.createLightFixtureBuilder(); // fixture = javaFixtureFactory.createCodeInsightFixture(fixtureBuilder.getFixture()); // fixture.setUp(); // } // // @After // public void tearDown() throws Exception { // fixture.tearDown(); // } // // @Nonnull // @CheckReturnValue // protected Application getApplication() { // if (fixture == null) { // throw new AssertionError("getApplication() must call after setUp()"); // } // return ApplicationManager.getApplication(); // } // // @Nonnull // @CheckReturnValue // protected Project getProject() { // if (fixture == null) { // throw new AssertionError("getProject() must call after setUp()"); // } // return fixture.getProject(); // } // } // // Path: idea/src/main/java/io/t28/json2java/idea/Json2JavaBundle.java // public class Json2JavaBundle extends AbstractBundle { // private static final String BUNDLE = "messages.Json2Java4IdeaBundle"; // // public Json2JavaBundle() { // super(BUNDLE); // } // // @Nonnull // public static Json2JavaBundle getInstance() { // return new Json2JavaBundle(); // } // // @Nonnull // @CheckReturnValue // public String message(@Nonnull @PropertyKey(resourceBundle = BUNDLE) String key, @Nonnull Object... objects) { // return getMessage(key, objects); // } // } // Path: idea/src/test/java/io/t28/json2java/idea/validator/ClassSuffixValidatorTest.java import com.intellij.openapi.project.Project; import com.intellij.psi.PsiNameHelper; import io.t28.json2java.idea.IdeaProjectTest; import io.t28.json2java.idea.Json2JavaBundle; import org.junit.Before; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; /* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.idea.validator; public class ClassSuffixValidatorTest extends IdeaProjectTest { private ClassSuffixValidator underTest; @Before @Override public void setUp() throws Exception { super.setUp(); final Project project = getProject();
final Json2JavaBundle bundle = Json2JavaBundle.getInstance();
t28hub/json2java4idea
idea/src/main/java/io/t28/json2java/idea/command/CommandActionFactory.java
// Path: core/src/main/java/io/t28/json2java/core/JavaConverter.java // public class JavaConverter { // private final Configuration configuration; // // public JavaConverter(@Nonnull Configuration configuration) { // this.configuration = configuration; // } // // @Nonnull // @CheckReturnValue // public String convert(@Nonnull String packageName, @Nonnull String className, @Nonnull String json) throws IOException { // final JsonValue value = configuration.jsonParser().parse(json); // final TypeSpec.Builder builder = fromValue(className, value).toBuilder(); // // Adding root class specific annotations // for (final AnnotationPolicy policy : configuration.annotationPolicies()) { // policy.apply(builder); // } // return configuration.javaBuilder().build(packageName, builder.build()); // } // // @Nonnull // @CheckReturnValue // @VisibleForTesting // TypeSpec fromValue(@Nonnull String className, @Nonnull JsonValue value) { // if (value.isObject()) { // return fromObject(className, value.asObject(), Modifier.PUBLIC); // } // // if (value.isArray()) { // return fromArray(className, value.asArray()); // } // // throw new IllegalArgumentException("value must be an Object or Array"); // } // // @Nonnull // private TypeSpec fromObject(@Nonnull String className, @Nonnull JsonObject object, @Nonnull Modifier... modifiers) { // final NamePolicy classNamePolicy = configuration.classNamePolicy(); // final ClassBuilder builder = configuration.classBuilder(); // builder.addModifiers(modifiers); // object.stream().forEach(child -> { // final String key = child.getKey(); // final JsonValue value = child.getValue(); // if (value.isObject()) { // final String innerClassName = classNamePolicy.convert(key, TypeName.OBJECT); // final TypeSpec innerClass = fromObject(innerClassName, value.asObject(), Modifier.PUBLIC, Modifier.STATIC); // builder.addInnerType(innerClass); // // final TypeName innerClassType = ClassName.bestGuess(innerClassName); // builder.addProperty(key, innerClassType); // return; // } // // if (value.isArray()) { // final String innerClassName = classNamePolicy.convert(key, TypeName.OBJECT); // final JsonValue firstValue = value.asArray().stream().findFirst().orElse(new JsonNull()); // final TypeName listType = generateListType(innerClassName, firstValue, builder); // builder.addProperty(key, listType); // return; // } // // builder.addProperty(key, value.getType()); // }); // return builder.build(className); // } // // @Nonnull // private TypeSpec fromArray(@Nonnull String className, @Nonnull JsonArray array) { // final JsonValue firstValue = array.stream().findFirst().orElse(new JsonNull()); // if (firstValue.isObject()) { // return fromValue(className, firstValue.asObject()); // } // // if (firstValue.isArray()) { // return fromArray(className, firstValue.asArray()); // } // // throw new IllegalArgumentException("Cannot create class from empty array or primitive array"); // } // // @Nonnull // private TypeName generateListType(@Nonnull String className, @Nonnull JsonValue value, @Nonnull ClassBuilder builder) { // if (value.isArray()) { // final JsonValue firstValue = value.asArray() // .stream() // .findFirst() // .orElse(new JsonNull()); // final TypeName type = generateListType(className, firstValue, builder); // return ParameterizedTypeName.get(ClassName.get(List.class), type); // } // // if (value.isObject()) { // final TypeSpec innerClass = fromObject(className, value.asObject(), Modifier.PUBLIC, Modifier.STATIC); // builder.addInnerType(innerClass); // // final TypeName innerClassType = ClassName.bestGuess(innerClass.name); // return ParameterizedTypeName.get(ClassName.get(List.class), innerClassType); // } // // return ParameterizedTypeName.get(ClassName.get(List.class), value.getType().box()); // } // }
import com.google.inject.assistedinject.Assisted; import com.intellij.psi.PsiDirectory; import io.t28.json2java.core.JavaConverter; import javax.annotation.CheckReturnValue; import javax.annotation.Nonnull;
/* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.idea.command; public interface CommandActionFactory { @Nonnull @CheckReturnValue NewClassCommandAction create( @Nonnull @Assisted("Name") String name, @Nonnull @Assisted("Json") String json, @Nonnull PsiDirectory directory,
// Path: core/src/main/java/io/t28/json2java/core/JavaConverter.java // public class JavaConverter { // private final Configuration configuration; // // public JavaConverter(@Nonnull Configuration configuration) { // this.configuration = configuration; // } // // @Nonnull // @CheckReturnValue // public String convert(@Nonnull String packageName, @Nonnull String className, @Nonnull String json) throws IOException { // final JsonValue value = configuration.jsonParser().parse(json); // final TypeSpec.Builder builder = fromValue(className, value).toBuilder(); // // Adding root class specific annotations // for (final AnnotationPolicy policy : configuration.annotationPolicies()) { // policy.apply(builder); // } // return configuration.javaBuilder().build(packageName, builder.build()); // } // // @Nonnull // @CheckReturnValue // @VisibleForTesting // TypeSpec fromValue(@Nonnull String className, @Nonnull JsonValue value) { // if (value.isObject()) { // return fromObject(className, value.asObject(), Modifier.PUBLIC); // } // // if (value.isArray()) { // return fromArray(className, value.asArray()); // } // // throw new IllegalArgumentException("value must be an Object or Array"); // } // // @Nonnull // private TypeSpec fromObject(@Nonnull String className, @Nonnull JsonObject object, @Nonnull Modifier... modifiers) { // final NamePolicy classNamePolicy = configuration.classNamePolicy(); // final ClassBuilder builder = configuration.classBuilder(); // builder.addModifiers(modifiers); // object.stream().forEach(child -> { // final String key = child.getKey(); // final JsonValue value = child.getValue(); // if (value.isObject()) { // final String innerClassName = classNamePolicy.convert(key, TypeName.OBJECT); // final TypeSpec innerClass = fromObject(innerClassName, value.asObject(), Modifier.PUBLIC, Modifier.STATIC); // builder.addInnerType(innerClass); // // final TypeName innerClassType = ClassName.bestGuess(innerClassName); // builder.addProperty(key, innerClassType); // return; // } // // if (value.isArray()) { // final String innerClassName = classNamePolicy.convert(key, TypeName.OBJECT); // final JsonValue firstValue = value.asArray().stream().findFirst().orElse(new JsonNull()); // final TypeName listType = generateListType(innerClassName, firstValue, builder); // builder.addProperty(key, listType); // return; // } // // builder.addProperty(key, value.getType()); // }); // return builder.build(className); // } // // @Nonnull // private TypeSpec fromArray(@Nonnull String className, @Nonnull JsonArray array) { // final JsonValue firstValue = array.stream().findFirst().orElse(new JsonNull()); // if (firstValue.isObject()) { // return fromValue(className, firstValue.asObject()); // } // // if (firstValue.isArray()) { // return fromArray(className, firstValue.asArray()); // } // // throw new IllegalArgumentException("Cannot create class from empty array or primitive array"); // } // // @Nonnull // private TypeName generateListType(@Nonnull String className, @Nonnull JsonValue value, @Nonnull ClassBuilder builder) { // if (value.isArray()) { // final JsonValue firstValue = value.asArray() // .stream() // .findFirst() // .orElse(new JsonNull()); // final TypeName type = generateListType(className, firstValue, builder); // return ParameterizedTypeName.get(ClassName.get(List.class), type); // } // // if (value.isObject()) { // final TypeSpec innerClass = fromObject(className, value.asObject(), Modifier.PUBLIC, Modifier.STATIC); // builder.addInnerType(innerClass); // // final TypeName innerClassType = ClassName.bestGuess(innerClass.name); // return ParameterizedTypeName.get(ClassName.get(List.class), innerClassType); // } // // return ParameterizedTypeName.get(ClassName.get(List.class), value.getType().box()); // } // } // Path: idea/src/main/java/io/t28/json2java/idea/command/CommandActionFactory.java import com.google.inject.assistedinject.Assisted; import com.intellij.psi.PsiDirectory; import io.t28.json2java.core.JavaConverter; import javax.annotation.CheckReturnValue; import javax.annotation.Nonnull; /* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.idea.command; public interface CommandActionFactory { @Nonnull @CheckReturnValue NewClassCommandAction create( @Nonnull @Assisted("Name") String name, @Nonnull @Assisted("Json") String json, @Nonnull PsiDirectory directory,
@Nonnull JavaConverter converter
t28hub/json2java4idea
idea/src/main/java/io/t28/json2java/idea/setting/TemporaryJson2JavaSettings.java
// Path: core/src/main/java/io/t28/json2java/core/Style.java // public enum Style { // NONE { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new ModelClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }, // GSON { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new GsonClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }, // JACKSON { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new JacksonClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }, // MOSHI { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new MoshiClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }; // // @Nonnull // @CheckReturnValue // abstract ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy); // // @Nonnull // @CheckReturnValue // public static Optional<Style> fromName(@Nonnull String name) { // return Stream.of(Style.values()) // .filter(style -> style.name().equalsIgnoreCase(name)) // .findFirst(); // } // // @Nonnull // @CheckReturnValue // public static Style fromName(@Nonnull String name, @Nonnull Style defaultStyle) { // return fromName(name).orElse(defaultStyle); // } // // public String get() { // return ""; // } // }
import io.t28.json2java.core.Style; import javax.annotation.Nonnull;
/* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.idea.setting; public class TemporaryJson2JavaSettings implements Json2JavaSettings { @Nonnull
// Path: core/src/main/java/io/t28/json2java/core/Style.java // public enum Style { // NONE { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new ModelClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }, // GSON { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new GsonClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }, // JACKSON { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new JacksonClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }, // MOSHI { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new MoshiClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }; // // @Nonnull // @CheckReturnValue // abstract ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy); // // @Nonnull // @CheckReturnValue // public static Optional<Style> fromName(@Nonnull String name) { // return Stream.of(Style.values()) // .filter(style -> style.name().equalsIgnoreCase(name)) // .findFirst(); // } // // @Nonnull // @CheckReturnValue // public static Style fromName(@Nonnull String name, @Nonnull Style defaultStyle) { // return fromName(name).orElse(defaultStyle); // } // // public String get() { // return ""; // } // } // Path: idea/src/main/java/io/t28/json2java/idea/setting/TemporaryJson2JavaSettings.java import io.t28.json2java.core.Style; import javax.annotation.Nonnull; /* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.idea.setting; public class TemporaryJson2JavaSettings implements Json2JavaSettings { @Nonnull
private Style style;
t28hub/json2java4idea
core/src/main/java/io/t28/json2java/core/io/JsonParser.java
// Path: core/src/main/java/io/t28/json2java/core/io/exception/JsonParseException.java // public class JsonParseException extends IOException { // private static final long serialVersionUID = 1477109671450199015L; // // public JsonParseException(@Nonnull String message, @Nonnull Throwable cause) { // super(message, cause); // } // } // // Path: core/src/main/java/io/t28/json2java/core/json/JsonValue.java // public abstract class JsonValue { // @Nonnull // @CheckReturnValue // public static JsonValue wrap(@Nullable Object value) { // return Stream.of(ValueType.values()) // .filter(type -> type.isAcceptable(value)) // .findFirst() // .orElseThrow(() -> new IllegalArgumentException("Unsupported type of value(" + value + ")")) // .wrap(value); // } // // @Nonnull // public abstract TypeName getType(); // // public abstract Object getValue(); // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("type", getType()) // .add("value", getValue()) // .toString(); // } // // @CheckReturnValue // public boolean isNull() { // return this instanceof JsonNull; // } // // @CheckReturnValue // public boolean isBoolean() { // return this instanceof JsonBoolean; // } // // @CheckReturnValue // public boolean isNumber() { // return this instanceof JsonNumber; // } // // @CheckReturnValue // public boolean isString() { // return this instanceof JsonString; // } // // @CheckReturnValue // public boolean isArray() { // return this instanceof JsonArray; // } // // @CheckReturnValue // public boolean isObject() { // return this instanceof JsonObject; // } // // @Nonnull // @CheckReturnValue // public JsonNull asNull() { // if (isNull()) { // return (JsonNull) this; // } // throw new IllegalStateException("This value is not a null"); // } // // @Nonnull // @CheckReturnValue // public JsonBoolean asBoolean() { // if (isBoolean()) { // return (JsonBoolean) this; // } // throw new IllegalStateException("This value is not a boolean"); // } // // @Nonnull // @CheckReturnValue // public JsonNumber asNumber() { // if (isNumber()) { // return (JsonNumber) this; // } // throw new IllegalStateException("This value is not a number"); // } // // @Nonnull // @CheckReturnValue // public JsonString asString() { // if (isString()) { // return (JsonString) this; // } // throw new IllegalStateException("This value is not a string"); // } // // @Nonnull // @CheckReturnValue // public JsonArray asArray() { // if (isArray()) { // return (JsonArray) this; // } // throw new IllegalStateException("This value is not an array"); // } // // @Nonnull // @CheckReturnValue // public JsonObject asObject() { // if (isObject()) { // return (JsonObject) this; // } // throw new IllegalStateException("This value is not an object"); // } // }
import io.t28.json2java.core.io.exception.JsonParseException; import io.t28.json2java.core.json.JsonValue; import javax.annotation.CheckReturnValue; import javax.annotation.Nonnull;
/* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.core.io; public interface JsonParser { @Nonnull @CheckReturnValue
// Path: core/src/main/java/io/t28/json2java/core/io/exception/JsonParseException.java // public class JsonParseException extends IOException { // private static final long serialVersionUID = 1477109671450199015L; // // public JsonParseException(@Nonnull String message, @Nonnull Throwable cause) { // super(message, cause); // } // } // // Path: core/src/main/java/io/t28/json2java/core/json/JsonValue.java // public abstract class JsonValue { // @Nonnull // @CheckReturnValue // public static JsonValue wrap(@Nullable Object value) { // return Stream.of(ValueType.values()) // .filter(type -> type.isAcceptable(value)) // .findFirst() // .orElseThrow(() -> new IllegalArgumentException("Unsupported type of value(" + value + ")")) // .wrap(value); // } // // @Nonnull // public abstract TypeName getType(); // // public abstract Object getValue(); // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("type", getType()) // .add("value", getValue()) // .toString(); // } // // @CheckReturnValue // public boolean isNull() { // return this instanceof JsonNull; // } // // @CheckReturnValue // public boolean isBoolean() { // return this instanceof JsonBoolean; // } // // @CheckReturnValue // public boolean isNumber() { // return this instanceof JsonNumber; // } // // @CheckReturnValue // public boolean isString() { // return this instanceof JsonString; // } // // @CheckReturnValue // public boolean isArray() { // return this instanceof JsonArray; // } // // @CheckReturnValue // public boolean isObject() { // return this instanceof JsonObject; // } // // @Nonnull // @CheckReturnValue // public JsonNull asNull() { // if (isNull()) { // return (JsonNull) this; // } // throw new IllegalStateException("This value is not a null"); // } // // @Nonnull // @CheckReturnValue // public JsonBoolean asBoolean() { // if (isBoolean()) { // return (JsonBoolean) this; // } // throw new IllegalStateException("This value is not a boolean"); // } // // @Nonnull // @CheckReturnValue // public JsonNumber asNumber() { // if (isNumber()) { // return (JsonNumber) this; // } // throw new IllegalStateException("This value is not a number"); // } // // @Nonnull // @CheckReturnValue // public JsonString asString() { // if (isString()) { // return (JsonString) this; // } // throw new IllegalStateException("This value is not a string"); // } // // @Nonnull // @CheckReturnValue // public JsonArray asArray() { // if (isArray()) { // return (JsonArray) this; // } // throw new IllegalStateException("This value is not an array"); // } // // @Nonnull // @CheckReturnValue // public JsonObject asObject() { // if (isObject()) { // return (JsonObject) this; // } // throw new IllegalStateException("This value is not an object"); // } // } // Path: core/src/main/java/io/t28/json2java/core/io/JsonParser.java import io.t28.json2java.core.io.exception.JsonParseException; import io.t28.json2java.core.json.JsonValue; import javax.annotation.CheckReturnValue; import javax.annotation.Nonnull; /* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.core.io; public interface JsonParser { @Nonnull @CheckReturnValue
JsonValue parse(@Nonnull String json) throws JsonParseException;
t28hub/json2java4idea
core/src/main/java/io/t28/json2java/core/io/JsonParser.java
// Path: core/src/main/java/io/t28/json2java/core/io/exception/JsonParseException.java // public class JsonParseException extends IOException { // private static final long serialVersionUID = 1477109671450199015L; // // public JsonParseException(@Nonnull String message, @Nonnull Throwable cause) { // super(message, cause); // } // } // // Path: core/src/main/java/io/t28/json2java/core/json/JsonValue.java // public abstract class JsonValue { // @Nonnull // @CheckReturnValue // public static JsonValue wrap(@Nullable Object value) { // return Stream.of(ValueType.values()) // .filter(type -> type.isAcceptable(value)) // .findFirst() // .orElseThrow(() -> new IllegalArgumentException("Unsupported type of value(" + value + ")")) // .wrap(value); // } // // @Nonnull // public abstract TypeName getType(); // // public abstract Object getValue(); // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("type", getType()) // .add("value", getValue()) // .toString(); // } // // @CheckReturnValue // public boolean isNull() { // return this instanceof JsonNull; // } // // @CheckReturnValue // public boolean isBoolean() { // return this instanceof JsonBoolean; // } // // @CheckReturnValue // public boolean isNumber() { // return this instanceof JsonNumber; // } // // @CheckReturnValue // public boolean isString() { // return this instanceof JsonString; // } // // @CheckReturnValue // public boolean isArray() { // return this instanceof JsonArray; // } // // @CheckReturnValue // public boolean isObject() { // return this instanceof JsonObject; // } // // @Nonnull // @CheckReturnValue // public JsonNull asNull() { // if (isNull()) { // return (JsonNull) this; // } // throw new IllegalStateException("This value is not a null"); // } // // @Nonnull // @CheckReturnValue // public JsonBoolean asBoolean() { // if (isBoolean()) { // return (JsonBoolean) this; // } // throw new IllegalStateException("This value is not a boolean"); // } // // @Nonnull // @CheckReturnValue // public JsonNumber asNumber() { // if (isNumber()) { // return (JsonNumber) this; // } // throw new IllegalStateException("This value is not a number"); // } // // @Nonnull // @CheckReturnValue // public JsonString asString() { // if (isString()) { // return (JsonString) this; // } // throw new IllegalStateException("This value is not a string"); // } // // @Nonnull // @CheckReturnValue // public JsonArray asArray() { // if (isArray()) { // return (JsonArray) this; // } // throw new IllegalStateException("This value is not an array"); // } // // @Nonnull // @CheckReturnValue // public JsonObject asObject() { // if (isObject()) { // return (JsonObject) this; // } // throw new IllegalStateException("This value is not an object"); // } // }
import io.t28.json2java.core.io.exception.JsonParseException; import io.t28.json2java.core.json.JsonValue; import javax.annotation.CheckReturnValue; import javax.annotation.Nonnull;
/* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.core.io; public interface JsonParser { @Nonnull @CheckReturnValue
// Path: core/src/main/java/io/t28/json2java/core/io/exception/JsonParseException.java // public class JsonParseException extends IOException { // private static final long serialVersionUID = 1477109671450199015L; // // public JsonParseException(@Nonnull String message, @Nonnull Throwable cause) { // super(message, cause); // } // } // // Path: core/src/main/java/io/t28/json2java/core/json/JsonValue.java // public abstract class JsonValue { // @Nonnull // @CheckReturnValue // public static JsonValue wrap(@Nullable Object value) { // return Stream.of(ValueType.values()) // .filter(type -> type.isAcceptable(value)) // .findFirst() // .orElseThrow(() -> new IllegalArgumentException("Unsupported type of value(" + value + ")")) // .wrap(value); // } // // @Nonnull // public abstract TypeName getType(); // // public abstract Object getValue(); // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("type", getType()) // .add("value", getValue()) // .toString(); // } // // @CheckReturnValue // public boolean isNull() { // return this instanceof JsonNull; // } // // @CheckReturnValue // public boolean isBoolean() { // return this instanceof JsonBoolean; // } // // @CheckReturnValue // public boolean isNumber() { // return this instanceof JsonNumber; // } // // @CheckReturnValue // public boolean isString() { // return this instanceof JsonString; // } // // @CheckReturnValue // public boolean isArray() { // return this instanceof JsonArray; // } // // @CheckReturnValue // public boolean isObject() { // return this instanceof JsonObject; // } // // @Nonnull // @CheckReturnValue // public JsonNull asNull() { // if (isNull()) { // return (JsonNull) this; // } // throw new IllegalStateException("This value is not a null"); // } // // @Nonnull // @CheckReturnValue // public JsonBoolean asBoolean() { // if (isBoolean()) { // return (JsonBoolean) this; // } // throw new IllegalStateException("This value is not a boolean"); // } // // @Nonnull // @CheckReturnValue // public JsonNumber asNumber() { // if (isNumber()) { // return (JsonNumber) this; // } // throw new IllegalStateException("This value is not a number"); // } // // @Nonnull // @CheckReturnValue // public JsonString asString() { // if (isString()) { // return (JsonString) this; // } // throw new IllegalStateException("This value is not a string"); // } // // @Nonnull // @CheckReturnValue // public JsonArray asArray() { // if (isArray()) { // return (JsonArray) this; // } // throw new IllegalStateException("This value is not an array"); // } // // @Nonnull // @CheckReturnValue // public JsonObject asObject() { // if (isObject()) { // return (JsonObject) this; // } // throw new IllegalStateException("This value is not an object"); // } // } // Path: core/src/main/java/io/t28/json2java/core/io/JsonParser.java import io.t28.json2java.core.io.exception.JsonParseException; import io.t28.json2java.core.json.JsonValue; import javax.annotation.CheckReturnValue; import javax.annotation.Nonnull; /* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.core.io; public interface JsonParser { @Nonnull @CheckReturnValue
JsonValue parse(@Nonnull String json) throws JsonParseException;
t28hub/json2java4idea
core/src/main/java/io/t28/json2java/core/io/JavaBuilderImpl.java
// Path: core/src/main/java/io/t28/json2java/core/io/JavaBuilder.java // public interface JavaBuilder { // @Nonnull // @CheckReturnValue // String build(@Nonnull String packageName, @Nonnull TypeSpec typeSpec) throws JavaBuildException; // } // // Path: core/src/main/java/io/t28/json2java/core/io/exception/JavaBuildException.java // public class JavaBuildException extends IOException { // private static final long serialVersionUID = 5642915429649238000L; // // public JavaBuildException(@Nonnull String message, @Nonnull Throwable cause) { // super(message, cause); // } // }
import com.squareup.javapoet.JavaFile; import com.squareup.javapoet.TypeSpec; import io.t28.json2java.core.io.JavaBuilder; import io.t28.json2java.core.io.exception.JavaBuildException; import javax.annotation.Nonnull;
/* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.core.io; public class JavaBuilderImpl implements JavaBuilder { private static final String INDENT = " "; @Nonnull @Override
// Path: core/src/main/java/io/t28/json2java/core/io/JavaBuilder.java // public interface JavaBuilder { // @Nonnull // @CheckReturnValue // String build(@Nonnull String packageName, @Nonnull TypeSpec typeSpec) throws JavaBuildException; // } // // Path: core/src/main/java/io/t28/json2java/core/io/exception/JavaBuildException.java // public class JavaBuildException extends IOException { // private static final long serialVersionUID = 5642915429649238000L; // // public JavaBuildException(@Nonnull String message, @Nonnull Throwable cause) { // super(message, cause); // } // } // Path: core/src/main/java/io/t28/json2java/core/io/JavaBuilderImpl.java import com.squareup.javapoet.JavaFile; import com.squareup.javapoet.TypeSpec; import io.t28.json2java.core.io.JavaBuilder; import io.t28.json2java.core.io.exception.JavaBuildException; import javax.annotation.Nonnull; /* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.core.io; public class JavaBuilderImpl implements JavaBuilder { private static final String INDENT = " "; @Nonnull @Override
public String build(@Nonnull String packageName, @Nonnull TypeSpec typeSpec) throws JavaBuildException {
t28hub/json2java4idea
core/src/test/java/io/t28/json2java/core/json/JsonBooleanTest.java
// Path: core/src/test/java/io/t28/json2java/core/Assertions.java // @Nonnull // @CheckReturnValue // public static JsonValueAssert assertThat(@Nullable JsonValue actual) { // return new JsonValueAssert(actual); // }
import com.squareup.javapoet.TypeName; import org.junit.Before; import org.junit.Test; import static io.t28.json2java.core.Assertions.assertThat;
/* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.core.json; public class JsonBooleanTest { private JsonBoolean underTest; @Before public void setUp() throws Exception { underTest = new JsonBoolean(true); } @Test public void getType() throws Exception { // exercise final TypeName actual = underTest.getType(); // verify
// Path: core/src/test/java/io/t28/json2java/core/Assertions.java // @Nonnull // @CheckReturnValue // public static JsonValueAssert assertThat(@Nullable JsonValue actual) { // return new JsonValueAssert(actual); // } // Path: core/src/test/java/io/t28/json2java/core/json/JsonBooleanTest.java import com.squareup.javapoet.TypeName; import org.junit.Before; import org.junit.Test; import static io.t28.json2java.core.Assertions.assertThat; /* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.core.json; public class JsonBooleanTest { private JsonBoolean underTest; @Before public void setUp() throws Exception { underTest = new JsonBoolean(true); } @Test public void getType() throws Exception { // exercise final TypeName actual = underTest.getType(); // verify
assertThat(actual)
t28hub/json2java4idea
idea/src/main/java/io/t28/json2java/idea/view/SettingsPanel.java
// Path: core/src/main/java/io/t28/json2java/core/Style.java // public enum Style { // NONE { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new ModelClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }, // GSON { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new GsonClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }, // JACKSON { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new JacksonClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }, // MOSHI { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new MoshiClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }; // // @Nonnull // @CheckReturnValue // abstract ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy); // // @Nonnull // @CheckReturnValue // public static Optional<Style> fromName(@Nonnull String name) { // return Stream.of(Style.values()) // .filter(style -> style.name().equalsIgnoreCase(name)) // .findFirst(); // } // // @Nonnull // @CheckReturnValue // public static Style fromName(@Nonnull String name, @Nonnull Style defaultStyle) { // return fromName(name).orElse(defaultStyle); // } // // public String get() { // return ""; // } // }
import com.google.common.annotations.VisibleForTesting; import com.intellij.ide.highlighter.JavaFileType; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.editor.CaretModel; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.EditorFactory; import com.intellij.openapi.editor.EditorSettings; import io.t28.json2java.core.Style; import javax.annotation.CheckReturnValue; import javax.annotation.Nonnull; import javax.swing.ButtonGroup; import javax.swing.ButtonModel; import javax.swing.JCheckBox; import javax.swing.JComponent; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JTextField; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Collections; import java.util.stream.Stream;
} @Override public void actionPerformed(@Nonnull ActionEvent event) { onChanged(); } @Override public void insertUpdate(@Nonnull DocumentEvent event) { onChanged(); } @Override public void removeUpdate(@Nonnull DocumentEvent event) { onChanged(); } @Override public void changedUpdate(@Nonnull DocumentEvent event) { onChanged(); } @Nonnull @CheckReturnValue public JComponent getComponent() { return rootPanel; } @Nonnull @CheckReturnValue
// Path: core/src/main/java/io/t28/json2java/core/Style.java // public enum Style { // NONE { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new ModelClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }, // GSON { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new GsonClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }, // JACKSON { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new JacksonClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }, // MOSHI { // @Nonnull // @Override // ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy) { // return new MoshiClassBuilder(fieldNameStrategy, methodNameStrategy, parameterNameStrategy); // } // }; // // @Nonnull // @CheckReturnValue // abstract ClassBuilder toBuilder(@Nonnull NamePolicy fieldNameStrategy, // @Nonnull NamePolicy methodNameStrategy, // @Nonnull NamePolicy parameterNameStrategy); // // @Nonnull // @CheckReturnValue // public static Optional<Style> fromName(@Nonnull String name) { // return Stream.of(Style.values()) // .filter(style -> style.name().equalsIgnoreCase(name)) // .findFirst(); // } // // @Nonnull // @CheckReturnValue // public static Style fromName(@Nonnull String name, @Nonnull Style defaultStyle) { // return fromName(name).orElse(defaultStyle); // } // // public String get() { // return ""; // } // } // Path: idea/src/main/java/io/t28/json2java/idea/view/SettingsPanel.java import com.google.common.annotations.VisibleForTesting; import com.intellij.ide.highlighter.JavaFileType; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.editor.CaretModel; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.EditorFactory; import com.intellij.openapi.editor.EditorSettings; import io.t28.json2java.core.Style; import javax.annotation.CheckReturnValue; import javax.annotation.Nonnull; import javax.swing.ButtonGroup; import javax.swing.ButtonModel; import javax.swing.JCheckBox; import javax.swing.JComponent; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JTextField; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Collections; import java.util.stream.Stream; } @Override public void actionPerformed(@Nonnull ActionEvent event) { onChanged(); } @Override public void insertUpdate(@Nonnull DocumentEvent event) { onChanged(); } @Override public void removeUpdate(@Nonnull DocumentEvent event) { onChanged(); } @Override public void changedUpdate(@Nonnull DocumentEvent event) { onChanged(); } @Nonnull @CheckReturnValue public JComponent getComponent() { return rootPanel; } @Nonnull @CheckReturnValue
public Style getStyle() {
t28hub/json2java4idea
core/src/test/java/io/t28/json2java/core/json/JsonValueTest.java
// Path: core/src/test/java/io/t28/json2java/core/Assertions.java // @Nonnull // @CheckReturnValue // public static JsonValueAssert assertThat(@Nullable JsonValue actual) { // return new JsonValueAssert(actual); // }
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import org.junit.Test; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Collections; import java.util.List; import java.util.Map; import static io.t28.json2java.core.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy;
/* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.core.json; public class JsonValueTest { @Test public void wrapShouldReturnJsonNullWhenNull() throws Exception { // exercise final JsonValue actual = JsonValue.wrap(null); // verify
// Path: core/src/test/java/io/t28/json2java/core/Assertions.java // @Nonnull // @CheckReturnValue // public static JsonValueAssert assertThat(@Nullable JsonValue actual) { // return new JsonValueAssert(actual); // } // Path: core/src/test/java/io/t28/json2java/core/json/JsonValueTest.java import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import org.junit.Test; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Collections; import java.util.List; import java.util.Map; import static io.t28.json2java.core.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; /* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.core.json; public class JsonValueTest { @Test public void wrapShouldReturnJsonNullWhenNull() throws Exception { // exercise final JsonValue actual = JsonValue.wrap(null); // verify
assertThat(actual)
t28hub/json2java4idea
core/src/test/java/io/t28/json2java/core/builder/MoshiClassBuilderTest.java
// Path: core/src/main/java/io/t28/json2java/core/naming/DefaultNamePolicy.java // public enum DefaultNamePolicy implements NamePolicy { // CLASS { // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // return format(name, CaseFormat.UPPER_CAMEL); // } // }, // METHOD { // private static final String BOOLEAN_PREFIX = "is"; // private static final String GENERAL_PREFIX = "get"; // // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // final StringBuilder builder = new StringBuilder(); // if (type.equals(TypeName.BOOLEAN) || type.equals(ClassName.get(Boolean.class))) { // builder.append(BOOLEAN_PREFIX); // } else { // builder.append(GENERAL_PREFIX); // } // return builder.append(format(name, CaseFormat.UPPER_CAMEL)) // .toString(); // } // }, // FIELD { // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // return format(name, CaseFormat.LOWER_CAMEL); // } // }, // PARAMETER { // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // return format(name, CaseFormat.LOWER_CAMEL); // } // }; // // private static final String NO_TEXT = ""; // private static final String DELIMITER = "_"; // private static final String DELIMITER_REGEX = "(_|-|\\s|\\.|:)"; // private static final String CAMEL_CASE_REGEX = "(?<!(^|[A-Z]))(?=[A-Z])|(?<!^)(?=[A-Z][a-z])"; // private static final String INVALID_IDENTIFIER_REGEX = "[^A-Za-z0-9_$]"; // // @Nonnull // @CheckReturnValue // public static String format(@Nonnull String name, @Nonnull CaseFormat format) { // final Matcher matcher = Pattern.compile(DELIMITER_REGEX).matcher(name); // final String pattern; // if (matcher.find()) { // pattern = DELIMITER_REGEX; // } else { // pattern = CAMEL_CASE_REGEX; // } // final String snakeCase = Stream.of(name.split(pattern)) // .map(Ascii::toLowerCase) // .map(part -> part.replaceAll(INVALID_IDENTIFIER_REGEX, NO_TEXT)) // .filter(part -> !Strings.isNullOrEmpty(part)) // .collect(Collectors.joining(DELIMITER)); // return CaseFormat.LOWER_UNDERSCORE.to(format, snakeCase); // } // } // // Path: core/src/test/java/io/t28/json2java/core/Assertions.java // @Nonnull // @CheckReturnValue // public static JsonValueAssert assertThat(@Nullable JsonValue actual) { // return new JsonValueAssert(actual); // }
import com.squareup.javapoet.AnnotationSpec; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.TypeName; import com.squareup.moshi.Json; import io.t28.json2java.core.naming.DefaultNamePolicy; import org.junit.Before; import org.junit.Test; import java.util.List; import static io.t28.json2java.core.Assertions.assertThat;
/* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.core.builder; public class MoshiClassBuilderTest { private MoshiClassBuilder underTest; @Before public void setUp() throws Exception { underTest = new MoshiClassBuilder(
// Path: core/src/main/java/io/t28/json2java/core/naming/DefaultNamePolicy.java // public enum DefaultNamePolicy implements NamePolicy { // CLASS { // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // return format(name, CaseFormat.UPPER_CAMEL); // } // }, // METHOD { // private static final String BOOLEAN_PREFIX = "is"; // private static final String GENERAL_PREFIX = "get"; // // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // final StringBuilder builder = new StringBuilder(); // if (type.equals(TypeName.BOOLEAN) || type.equals(ClassName.get(Boolean.class))) { // builder.append(BOOLEAN_PREFIX); // } else { // builder.append(GENERAL_PREFIX); // } // return builder.append(format(name, CaseFormat.UPPER_CAMEL)) // .toString(); // } // }, // FIELD { // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // return format(name, CaseFormat.LOWER_CAMEL); // } // }, // PARAMETER { // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // return format(name, CaseFormat.LOWER_CAMEL); // } // }; // // private static final String NO_TEXT = ""; // private static final String DELIMITER = "_"; // private static final String DELIMITER_REGEX = "(_|-|\\s|\\.|:)"; // private static final String CAMEL_CASE_REGEX = "(?<!(^|[A-Z]))(?=[A-Z])|(?<!^)(?=[A-Z][a-z])"; // private static final String INVALID_IDENTIFIER_REGEX = "[^A-Za-z0-9_$]"; // // @Nonnull // @CheckReturnValue // public static String format(@Nonnull String name, @Nonnull CaseFormat format) { // final Matcher matcher = Pattern.compile(DELIMITER_REGEX).matcher(name); // final String pattern; // if (matcher.find()) { // pattern = DELIMITER_REGEX; // } else { // pattern = CAMEL_CASE_REGEX; // } // final String snakeCase = Stream.of(name.split(pattern)) // .map(Ascii::toLowerCase) // .map(part -> part.replaceAll(INVALID_IDENTIFIER_REGEX, NO_TEXT)) // .filter(part -> !Strings.isNullOrEmpty(part)) // .collect(Collectors.joining(DELIMITER)); // return CaseFormat.LOWER_UNDERSCORE.to(format, snakeCase); // } // } // // Path: core/src/test/java/io/t28/json2java/core/Assertions.java // @Nonnull // @CheckReturnValue // public static JsonValueAssert assertThat(@Nullable JsonValue actual) { // return new JsonValueAssert(actual); // } // Path: core/src/test/java/io/t28/json2java/core/builder/MoshiClassBuilderTest.java import com.squareup.javapoet.AnnotationSpec; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.TypeName; import com.squareup.moshi.Json; import io.t28.json2java.core.naming.DefaultNamePolicy; import org.junit.Before; import org.junit.Test; import java.util.List; import static io.t28.json2java.core.Assertions.assertThat; /* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.core.builder; public class MoshiClassBuilderTest { private MoshiClassBuilder underTest; @Before public void setUp() throws Exception { underTest = new MoshiClassBuilder(
DefaultNamePolicy.FIELD,
t28hub/json2java4idea
core/src/test/java/io/t28/json2java/core/builder/MoshiClassBuilderTest.java
// Path: core/src/main/java/io/t28/json2java/core/naming/DefaultNamePolicy.java // public enum DefaultNamePolicy implements NamePolicy { // CLASS { // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // return format(name, CaseFormat.UPPER_CAMEL); // } // }, // METHOD { // private static final String BOOLEAN_PREFIX = "is"; // private static final String GENERAL_PREFIX = "get"; // // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // final StringBuilder builder = new StringBuilder(); // if (type.equals(TypeName.BOOLEAN) || type.equals(ClassName.get(Boolean.class))) { // builder.append(BOOLEAN_PREFIX); // } else { // builder.append(GENERAL_PREFIX); // } // return builder.append(format(name, CaseFormat.UPPER_CAMEL)) // .toString(); // } // }, // FIELD { // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // return format(name, CaseFormat.LOWER_CAMEL); // } // }, // PARAMETER { // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // return format(name, CaseFormat.LOWER_CAMEL); // } // }; // // private static final String NO_TEXT = ""; // private static final String DELIMITER = "_"; // private static final String DELIMITER_REGEX = "(_|-|\\s|\\.|:)"; // private static final String CAMEL_CASE_REGEX = "(?<!(^|[A-Z]))(?=[A-Z])|(?<!^)(?=[A-Z][a-z])"; // private static final String INVALID_IDENTIFIER_REGEX = "[^A-Za-z0-9_$]"; // // @Nonnull // @CheckReturnValue // public static String format(@Nonnull String name, @Nonnull CaseFormat format) { // final Matcher matcher = Pattern.compile(DELIMITER_REGEX).matcher(name); // final String pattern; // if (matcher.find()) { // pattern = DELIMITER_REGEX; // } else { // pattern = CAMEL_CASE_REGEX; // } // final String snakeCase = Stream.of(name.split(pattern)) // .map(Ascii::toLowerCase) // .map(part -> part.replaceAll(INVALID_IDENTIFIER_REGEX, NO_TEXT)) // .filter(part -> !Strings.isNullOrEmpty(part)) // .collect(Collectors.joining(DELIMITER)); // return CaseFormat.LOWER_UNDERSCORE.to(format, snakeCase); // } // } // // Path: core/src/test/java/io/t28/json2java/core/Assertions.java // @Nonnull // @CheckReturnValue // public static JsonValueAssert assertThat(@Nullable JsonValue actual) { // return new JsonValueAssert(actual); // }
import com.squareup.javapoet.AnnotationSpec; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.TypeName; import com.squareup.moshi.Json; import io.t28.json2java.core.naming.DefaultNamePolicy; import org.junit.Before; import org.junit.Test; import java.util.List; import static io.t28.json2java.core.Assertions.assertThat;
/* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.core.builder; public class MoshiClassBuilderTest { private MoshiClassBuilder underTest; @Before public void setUp() throws Exception { underTest = new MoshiClassBuilder( DefaultNamePolicy.FIELD, DefaultNamePolicy.METHOD, DefaultNamePolicy.PARAMETER ); } @Test public void buildFields() throws Exception { // setup underTest.addProperty("foo", TypeName.INT) .addProperty("bar", TypeName.OBJECT) .addProperty("baz", TypeName.BOOLEAN); // exercise final List<FieldSpec> actual = underTest.buildFields(); // verify
// Path: core/src/main/java/io/t28/json2java/core/naming/DefaultNamePolicy.java // public enum DefaultNamePolicy implements NamePolicy { // CLASS { // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // return format(name, CaseFormat.UPPER_CAMEL); // } // }, // METHOD { // private static final String BOOLEAN_PREFIX = "is"; // private static final String GENERAL_PREFIX = "get"; // // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // final StringBuilder builder = new StringBuilder(); // if (type.equals(TypeName.BOOLEAN) || type.equals(ClassName.get(Boolean.class))) { // builder.append(BOOLEAN_PREFIX); // } else { // builder.append(GENERAL_PREFIX); // } // return builder.append(format(name, CaseFormat.UPPER_CAMEL)) // .toString(); // } // }, // FIELD { // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // return format(name, CaseFormat.LOWER_CAMEL); // } // }, // PARAMETER { // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // return format(name, CaseFormat.LOWER_CAMEL); // } // }; // // private static final String NO_TEXT = ""; // private static final String DELIMITER = "_"; // private static final String DELIMITER_REGEX = "(_|-|\\s|\\.|:)"; // private static final String CAMEL_CASE_REGEX = "(?<!(^|[A-Z]))(?=[A-Z])|(?<!^)(?=[A-Z][a-z])"; // private static final String INVALID_IDENTIFIER_REGEX = "[^A-Za-z0-9_$]"; // // @Nonnull // @CheckReturnValue // public static String format(@Nonnull String name, @Nonnull CaseFormat format) { // final Matcher matcher = Pattern.compile(DELIMITER_REGEX).matcher(name); // final String pattern; // if (matcher.find()) { // pattern = DELIMITER_REGEX; // } else { // pattern = CAMEL_CASE_REGEX; // } // final String snakeCase = Stream.of(name.split(pattern)) // .map(Ascii::toLowerCase) // .map(part -> part.replaceAll(INVALID_IDENTIFIER_REGEX, NO_TEXT)) // .filter(part -> !Strings.isNullOrEmpty(part)) // .collect(Collectors.joining(DELIMITER)); // return CaseFormat.LOWER_UNDERSCORE.to(format, snakeCase); // } // } // // Path: core/src/test/java/io/t28/json2java/core/Assertions.java // @Nonnull // @CheckReturnValue // public static JsonValueAssert assertThat(@Nullable JsonValue actual) { // return new JsonValueAssert(actual); // } // Path: core/src/test/java/io/t28/json2java/core/builder/MoshiClassBuilderTest.java import com.squareup.javapoet.AnnotationSpec; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.TypeName; import com.squareup.moshi.Json; import io.t28.json2java.core.naming.DefaultNamePolicy; import org.junit.Before; import org.junit.Test; import java.util.List; import static io.t28.json2java.core.Assertions.assertThat; /* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.core.builder; public class MoshiClassBuilderTest { private MoshiClassBuilder underTest; @Before public void setUp() throws Exception { underTest = new MoshiClassBuilder( DefaultNamePolicy.FIELD, DefaultNamePolicy.METHOD, DefaultNamePolicy.PARAMETER ); } @Test public void buildFields() throws Exception { // setup underTest.addProperty("foo", TypeName.INT) .addProperty("bar", TypeName.OBJECT) .addProperty("baz", TypeName.BOOLEAN); // exercise final List<FieldSpec> actual = underTest.buildFields(); // verify
assertThat(actual)
t28hub/json2java4idea
idea/src/main/java/io/t28/json2java/idea/naming/ParameterNamePolicy.java
// Path: core/src/main/java/io/t28/json2java/core/naming/DefaultNamePolicy.java // public enum DefaultNamePolicy implements NamePolicy { // CLASS { // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // return format(name, CaseFormat.UPPER_CAMEL); // } // }, // METHOD { // private static final String BOOLEAN_PREFIX = "is"; // private static final String GENERAL_PREFIX = "get"; // // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // final StringBuilder builder = new StringBuilder(); // if (type.equals(TypeName.BOOLEAN) || type.equals(ClassName.get(Boolean.class))) { // builder.append(BOOLEAN_PREFIX); // } else { // builder.append(GENERAL_PREFIX); // } // return builder.append(format(name, CaseFormat.UPPER_CAMEL)) // .toString(); // } // }, // FIELD { // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // return format(name, CaseFormat.LOWER_CAMEL); // } // }, // PARAMETER { // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // return format(name, CaseFormat.LOWER_CAMEL); // } // }; // // private static final String NO_TEXT = ""; // private static final String DELIMITER = "_"; // private static final String DELIMITER_REGEX = "(_|-|\\s|\\.|:)"; // private static final String CAMEL_CASE_REGEX = "(?<!(^|[A-Z]))(?=[A-Z])|(?<!^)(?=[A-Z][a-z])"; // private static final String INVALID_IDENTIFIER_REGEX = "[^A-Za-z0-9_$]"; // // @Nonnull // @CheckReturnValue // public static String format(@Nonnull String name, @Nonnull CaseFormat format) { // final Matcher matcher = Pattern.compile(DELIMITER_REGEX).matcher(name); // final String pattern; // if (matcher.find()) { // pattern = DELIMITER_REGEX; // } else { // pattern = CAMEL_CASE_REGEX; // } // final String snakeCase = Stream.of(name.split(pattern)) // .map(Ascii::toLowerCase) // .map(part -> part.replaceAll(INVALID_IDENTIFIER_REGEX, NO_TEXT)) // .filter(part -> !Strings.isNullOrEmpty(part)) // .collect(Collectors.joining(DELIMITER)); // return CaseFormat.LOWER_UNDERSCORE.to(format, snakeCase); // } // } // // Path: core/src/main/java/io/t28/json2java/core/naming/NamePolicy.java // public interface NamePolicy { // @Nonnull // @CheckReturnValue // String convert(@Nonnull String name, @Nonnull TypeName type); // }
import com.google.common.base.CaseFormat; import com.google.common.base.Strings; import com.google.inject.Inject; import com.intellij.psi.codeStyle.JavaCodeStyleManager; import com.intellij.psi.codeStyle.VariableKind; import com.squareup.javapoet.TypeName; import io.t28.json2java.core.naming.DefaultNamePolicy; import io.t28.json2java.core.naming.NamePolicy; import javax.annotation.Nonnull;
/* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.idea.naming; public class ParameterNamePolicy implements NamePolicy { private final JavaCodeStyleManager codeStyleManager; @Inject public ParameterNamePolicy(@Nonnull JavaCodeStyleManager codeStyleManager) { this.codeStyleManager = codeStyleManager; } @Nonnull @Override public String convert(@Nonnull String name, @Nonnull TypeName type) {
// Path: core/src/main/java/io/t28/json2java/core/naming/DefaultNamePolicy.java // public enum DefaultNamePolicy implements NamePolicy { // CLASS { // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // return format(name, CaseFormat.UPPER_CAMEL); // } // }, // METHOD { // private static final String BOOLEAN_PREFIX = "is"; // private static final String GENERAL_PREFIX = "get"; // // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // final StringBuilder builder = new StringBuilder(); // if (type.equals(TypeName.BOOLEAN) || type.equals(ClassName.get(Boolean.class))) { // builder.append(BOOLEAN_PREFIX); // } else { // builder.append(GENERAL_PREFIX); // } // return builder.append(format(name, CaseFormat.UPPER_CAMEL)) // .toString(); // } // }, // FIELD { // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // return format(name, CaseFormat.LOWER_CAMEL); // } // }, // PARAMETER { // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // return format(name, CaseFormat.LOWER_CAMEL); // } // }; // // private static final String NO_TEXT = ""; // private static final String DELIMITER = "_"; // private static final String DELIMITER_REGEX = "(_|-|\\s|\\.|:)"; // private static final String CAMEL_CASE_REGEX = "(?<!(^|[A-Z]))(?=[A-Z])|(?<!^)(?=[A-Z][a-z])"; // private static final String INVALID_IDENTIFIER_REGEX = "[^A-Za-z0-9_$]"; // // @Nonnull // @CheckReturnValue // public static String format(@Nonnull String name, @Nonnull CaseFormat format) { // final Matcher matcher = Pattern.compile(DELIMITER_REGEX).matcher(name); // final String pattern; // if (matcher.find()) { // pattern = DELIMITER_REGEX; // } else { // pattern = CAMEL_CASE_REGEX; // } // final String snakeCase = Stream.of(name.split(pattern)) // .map(Ascii::toLowerCase) // .map(part -> part.replaceAll(INVALID_IDENTIFIER_REGEX, NO_TEXT)) // .filter(part -> !Strings.isNullOrEmpty(part)) // .collect(Collectors.joining(DELIMITER)); // return CaseFormat.LOWER_UNDERSCORE.to(format, snakeCase); // } // } // // Path: core/src/main/java/io/t28/json2java/core/naming/NamePolicy.java // public interface NamePolicy { // @Nonnull // @CheckReturnValue // String convert(@Nonnull String name, @Nonnull TypeName type); // } // Path: idea/src/main/java/io/t28/json2java/idea/naming/ParameterNamePolicy.java import com.google.common.base.CaseFormat; import com.google.common.base.Strings; import com.google.inject.Inject; import com.intellij.psi.codeStyle.JavaCodeStyleManager; import com.intellij.psi.codeStyle.VariableKind; import com.squareup.javapoet.TypeName; import io.t28.json2java.core.naming.DefaultNamePolicy; import io.t28.json2java.core.naming.NamePolicy; import javax.annotation.Nonnull; /* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.idea.naming; public class ParameterNamePolicy implements NamePolicy { private final JavaCodeStyleManager codeStyleManager; @Inject public ParameterNamePolicy(@Nonnull JavaCodeStyleManager codeStyleManager) { this.codeStyleManager = codeStyleManager; } @Nonnull @Override public String convert(@Nonnull String name, @Nonnull TypeName type) {
final String propertyName = DefaultNamePolicy.format(name, CaseFormat.LOWER_CAMEL);
t28hub/json2java4idea
core/src/test/java/io/t28/json2java/core/json/ValueTypeTest.java
// Path: core/src/test/java/io/t28/json2java/core/Assertions.java // @Nonnull // @CheckReturnValue // public static JsonValueAssert assertThat(@Nullable JsonValue actual) { // return new JsonValueAssert(actual); // }
import static io.t28.json2java.core.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import org.jooq.lambda.tuple.Tuple; import org.jooq.lambda.tuple.Tuple3; import org.junit.Test; import org.junit.experimental.runners.Enclosed; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import javax.annotation.Nonnull; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Arrays; import java.util.Collection; import java.util.Collections;
Tuple.tuple(ValueType.DOUBLE, 1.0f, false), Tuple.tuple(ValueType.BIG_INTEGER, BigInteger.ONE, true), Tuple.tuple(ValueType.BIG_INTEGER, 1, false), Tuple.tuple(ValueType.BIG_DECIMAL, BigDecimal.ONE, true), Tuple.tuple(ValueType.BIG_DECIMAL, 1, false), Tuple.tuple(ValueType.STRING, "text", true), Tuple.tuple(ValueType.STRING, null, false), Tuple.tuple(ValueType.ARRAY, Collections.singletonList("test"), true), Tuple.tuple(ValueType.ARRAY, null, false), Tuple.tuple(ValueType.OBJECT, Collections.singletonMap("key", "test"), true), Tuple.tuple(ValueType.OBJECT, null, false) ); } private final ValueType underTest; private final Object value; private final boolean expected; public IsAcceptableTest(@Nonnull Tuple3<ValueType, Object, Boolean> fixture) { underTest = fixture.v1(); value = fixture.v2(); expected = fixture.v3(); } @Test public void isAcceptable() throws Exception { // exercise final boolean actual = underTest.isAcceptable(value); // verify
// Path: core/src/test/java/io/t28/json2java/core/Assertions.java // @Nonnull // @CheckReturnValue // public static JsonValueAssert assertThat(@Nullable JsonValue actual) { // return new JsonValueAssert(actual); // } // Path: core/src/test/java/io/t28/json2java/core/json/ValueTypeTest.java import static io.t28.json2java.core.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import org.jooq.lambda.tuple.Tuple; import org.jooq.lambda.tuple.Tuple3; import org.junit.Test; import org.junit.experimental.runners.Enclosed; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import javax.annotation.Nonnull; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Arrays; import java.util.Collection; import java.util.Collections; Tuple.tuple(ValueType.DOUBLE, 1.0f, false), Tuple.tuple(ValueType.BIG_INTEGER, BigInteger.ONE, true), Tuple.tuple(ValueType.BIG_INTEGER, 1, false), Tuple.tuple(ValueType.BIG_DECIMAL, BigDecimal.ONE, true), Tuple.tuple(ValueType.BIG_DECIMAL, 1, false), Tuple.tuple(ValueType.STRING, "text", true), Tuple.tuple(ValueType.STRING, null, false), Tuple.tuple(ValueType.ARRAY, Collections.singletonList("test"), true), Tuple.tuple(ValueType.ARRAY, null, false), Tuple.tuple(ValueType.OBJECT, Collections.singletonMap("key", "test"), true), Tuple.tuple(ValueType.OBJECT, null, false) ); } private final ValueType underTest; private final Object value; private final boolean expected; public IsAcceptableTest(@Nonnull Tuple3<ValueType, Object, Boolean> fixture) { underTest = fixture.v1(); value = fixture.v2(); expected = fixture.v3(); } @Test public void isAcceptable() throws Exception { // exercise final boolean actual = underTest.isAcceptable(value); // verify
assertThat(actual).isEqualTo(expected);
t28hub/json2java4idea
core/src/test/java/io/t28/json2java/core/io/JavaBuilderImplTest.java
// Path: core/src/test/java/io/t28/json2java/core/Assertions.java // @Nonnull // @CheckReturnValue // public static JsonValueAssert assertThat(@Nullable JsonValue actual) { // return new JsonValueAssert(actual); // }
import com.squareup.javapoet.TypeSpec; import org.junit.Before; import org.junit.Test; import javax.lang.model.element.Modifier; import static io.t28.json2java.core.Assertions.assertThat;
/* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.core.io; public class JavaBuilderImplTest { private JavaBuilderImpl underTest; @Before public void setUp() throws Exception { underTest = new JavaBuilderImpl(); } @Test public void buildShouldReturnJavaCode() throws Exception { final TypeSpec typeSpec = TypeSpec.classBuilder("Test") .addModifiers(Modifier.PUBLIC) .build(); // exercise final String actual = underTest.build("io.t28.example", typeSpec); // verify
// Path: core/src/test/java/io/t28/json2java/core/Assertions.java // @Nonnull // @CheckReturnValue // public static JsonValueAssert assertThat(@Nullable JsonValue actual) { // return new JsonValueAssert(actual); // } // Path: core/src/test/java/io/t28/json2java/core/io/JavaBuilderImplTest.java import com.squareup.javapoet.TypeSpec; import org.junit.Before; import org.junit.Test; import javax.lang.model.element.Modifier; import static io.t28.json2java.core.Assertions.assertThat; /* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.core.io; public class JavaBuilderImplTest { private JavaBuilderImpl underTest; @Before public void setUp() throws Exception { underTest = new JavaBuilderImpl(); } @Test public void buildShouldReturnJavaCode() throws Exception { final TypeSpec typeSpec = TypeSpec.classBuilder("Test") .addModifiers(Modifier.PUBLIC) .build(); // exercise final String actual = underTest.build("io.t28.example", typeSpec); // verify
assertThat(actual)
t28hub/json2java4idea
core/src/test/java/io/t28/json2java/core/json/JsonNullTest.java
// Path: core/src/test/java/io/t28/json2java/core/Assertions.java // @Nonnull // @CheckReturnValue // public static JsonValueAssert assertThat(@Nullable JsonValue actual) { // return new JsonValueAssert(actual); // }
import com.squareup.javapoet.TypeName; import org.junit.Before; import org.junit.Test; import static io.t28.json2java.core.Assertions.assertThat;
/* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.core.json; public class JsonNullTest { private JsonNull underTest; @Before public void setUp() throws Exception { underTest = new JsonNull(); } @Test public void getType() throws Exception { // exercise final TypeName actual = underTest.getType(); // verify
// Path: core/src/test/java/io/t28/json2java/core/Assertions.java // @Nonnull // @CheckReturnValue // public static JsonValueAssert assertThat(@Nullable JsonValue actual) { // return new JsonValueAssert(actual); // } // Path: core/src/test/java/io/t28/json2java/core/json/JsonNullTest.java import com.squareup.javapoet.TypeName; import org.junit.Before; import org.junit.Test; import static io.t28.json2java.core.Assertions.assertThat; /* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.core.json; public class JsonNullTest { private JsonNull underTest; @Before public void setUp() throws Exception { underTest = new JsonNull(); } @Test public void getType() throws Exception { // exercise final TypeName actual = underTest.getType(); // verify
assertThat(actual)
t28hub/json2java4idea
core/src/test/java/io/t28/json2java/core/json/JsonObjectTest.java
// Path: core/src/test/java/io/t28/json2java/core/Assertions.java // @Nonnull // @CheckReturnValue // public static JsonValueAssert assertThat(@Nullable JsonValue actual) { // return new JsonValueAssert(actual); // }
import com.google.common.collect.ImmutableMap; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import org.junit.Before; import org.junit.Test; import java.util.Map; import java.util.stream.Stream; import static io.t28.json2java.core.Assertions.assertThat;
/* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.core.json; public class JsonObjectTest { private JsonObject underTest; @Before public void setUp() throws Exception { underTest = new JsonObject(ImmutableMap.of("foo", 42, "bar", 32)); } @Test public void getType() throws Exception { //exercise final TypeName actual = underTest.getType(); // verify
// Path: core/src/test/java/io/t28/json2java/core/Assertions.java // @Nonnull // @CheckReturnValue // public static JsonValueAssert assertThat(@Nullable JsonValue actual) { // return new JsonValueAssert(actual); // } // Path: core/src/test/java/io/t28/json2java/core/json/JsonObjectTest.java import com.google.common.collect.ImmutableMap; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import org.junit.Before; import org.junit.Test; import java.util.Map; import java.util.stream.Stream; import static io.t28.json2java.core.Assertions.assertThat; /* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.core.json; public class JsonObjectTest { private JsonObject underTest; @Before public void setUp() throws Exception { underTest = new JsonObject(ImmutableMap.of("foo", 42, "bar", 32)); } @Test public void getType() throws Exception { //exercise final TypeName actual = underTest.getType(); // verify
assertThat(actual)
t28hub/json2java4idea
idea/src/main/java/io/t28/json2java/idea/view/NewClassDialog.java
// Path: idea/src/main/java/io/t28/json2java/idea/Json2JavaBundle.java // public class Json2JavaBundle extends AbstractBundle { // private static final String BUNDLE = "messages.Json2Java4IdeaBundle"; // // public Json2JavaBundle() { // super(BUNDLE); // } // // @Nonnull // public static Json2JavaBundle getInstance() { // return new Json2JavaBundle(); // } // // @Nonnull // @CheckReturnValue // public String message(@Nonnull @PropertyKey(resourceBundle = BUNDLE) String key, @Nonnull Object... objects) { // return getMessage(key, objects); // } // } // // Path: idea/src/main/java/io/t28/json2java/idea/validator/NullValidator.java // public class NullValidator implements InputValidator { // @Override // public boolean checkInput(@Nullable String text) { // return false; // } // // @Override // public boolean canClose(@Nullable String text) { // return false; // } // }
import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; import com.intellij.json.JsonFileType; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.editor.CaretModel; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.EditorFactory; import com.intellij.openapi.editor.EditorSettings; import com.intellij.openapi.editor.colors.EditorColors; import com.intellij.openapi.editor.colors.EditorColorsScheme; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.ui.InputValidator; import com.intellij.openapi.ui.InputValidatorEx; import com.intellij.openapi.ui.ValidationInfo; import io.t28.json2java.idea.Json2JavaBundle; import io.t28.json2java.idea.validator.NullValidator; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jooq.lambda.tuple.Tuple; import javax.annotation.CheckReturnValue; import javax.annotation.Nonnull; import javax.swing.Action; import javax.swing.JComponent; import javax.swing.JPanel; import javax.swing.JTextField; import java.awt.event.ActionEvent;
/* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.idea.view; public class NewClassDialog extends DialogWrapper { private static final String EMPTY_TEXT = ""; private static final int INITIAL_OFFSET = 0; private final Project project;
// Path: idea/src/main/java/io/t28/json2java/idea/Json2JavaBundle.java // public class Json2JavaBundle extends AbstractBundle { // private static final String BUNDLE = "messages.Json2Java4IdeaBundle"; // // public Json2JavaBundle() { // super(BUNDLE); // } // // @Nonnull // public static Json2JavaBundle getInstance() { // return new Json2JavaBundle(); // } // // @Nonnull // @CheckReturnValue // public String message(@Nonnull @PropertyKey(resourceBundle = BUNDLE) String key, @Nonnull Object... objects) { // return getMessage(key, objects); // } // } // // Path: idea/src/main/java/io/t28/json2java/idea/validator/NullValidator.java // public class NullValidator implements InputValidator { // @Override // public boolean checkInput(@Nullable String text) { // return false; // } // // @Override // public boolean canClose(@Nullable String text) { // return false; // } // } // Path: idea/src/main/java/io/t28/json2java/idea/view/NewClassDialog.java import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; import com.intellij.json.JsonFileType; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.editor.CaretModel; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.EditorFactory; import com.intellij.openapi.editor.EditorSettings; import com.intellij.openapi.editor.colors.EditorColors; import com.intellij.openapi.editor.colors.EditorColorsScheme; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.ui.InputValidator; import com.intellij.openapi.ui.InputValidatorEx; import com.intellij.openapi.ui.ValidationInfo; import io.t28.json2java.idea.Json2JavaBundle; import io.t28.json2java.idea.validator.NullValidator; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jooq.lambda.tuple.Tuple; import javax.annotation.CheckReturnValue; import javax.annotation.Nonnull; import javax.swing.Action; import javax.swing.JComponent; import javax.swing.JPanel; import javax.swing.JTextField; import java.awt.event.ActionEvent; /* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.idea.view; public class NewClassDialog extends DialogWrapper { private static final String EMPTY_TEXT = ""; private static final int INITIAL_OFFSET = 0; private final Project project;
private final Json2JavaBundle bundle;
t28hub/json2java4idea
idea/src/main/java/io/t28/json2java/idea/view/NewClassDialog.java
// Path: idea/src/main/java/io/t28/json2java/idea/Json2JavaBundle.java // public class Json2JavaBundle extends AbstractBundle { // private static final String BUNDLE = "messages.Json2Java4IdeaBundle"; // // public Json2JavaBundle() { // super(BUNDLE); // } // // @Nonnull // public static Json2JavaBundle getInstance() { // return new Json2JavaBundle(); // } // // @Nonnull // @CheckReturnValue // public String message(@Nonnull @PropertyKey(resourceBundle = BUNDLE) String key, @Nonnull Object... objects) { // return getMessage(key, objects); // } // } // // Path: idea/src/main/java/io/t28/json2java/idea/validator/NullValidator.java // public class NullValidator implements InputValidator { // @Override // public boolean checkInput(@Nullable String text) { // return false; // } // // @Override // public boolean canClose(@Nullable String text) { // return false; // } // }
import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; import com.intellij.json.JsonFileType; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.editor.CaretModel; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.EditorFactory; import com.intellij.openapi.editor.EditorSettings; import com.intellij.openapi.editor.colors.EditorColors; import com.intellij.openapi.editor.colors.EditorColorsScheme; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.ui.InputValidator; import com.intellij.openapi.ui.InputValidatorEx; import com.intellij.openapi.ui.ValidationInfo; import io.t28.json2java.idea.Json2JavaBundle; import io.t28.json2java.idea.validator.NullValidator; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jooq.lambda.tuple.Tuple; import javax.annotation.CheckReturnValue; import javax.annotation.Nonnull; import javax.swing.Action; import javax.swing.JComponent; import javax.swing.JPanel; import javax.swing.JTextField; import java.awt.event.ActionEvent;
if (isEnabled()) { actionListener.onSettings(NewClassDialog.this); } } } public interface ActionListener { default void onOk(@Nonnull NewClassDialog dialog) { } default void onCancel(@Nonnull NewClassDialog dialog) { } default void onFormat(@Nonnull NewClassDialog dialog) { } default void onSettings(@Nonnull NewClassDialog dialog) { } } public static class Builder { private final Project project; private final Json2JavaBundle bundle; private InputValidator nameValidator; private InputValidator jsonValidator; private ActionListener actionListener; private Builder(@NotNull Project project, @Nonnull Json2JavaBundle bundle) { this.project = project; this.bundle = bundle;
// Path: idea/src/main/java/io/t28/json2java/idea/Json2JavaBundle.java // public class Json2JavaBundle extends AbstractBundle { // private static final String BUNDLE = "messages.Json2Java4IdeaBundle"; // // public Json2JavaBundle() { // super(BUNDLE); // } // // @Nonnull // public static Json2JavaBundle getInstance() { // return new Json2JavaBundle(); // } // // @Nonnull // @CheckReturnValue // public String message(@Nonnull @PropertyKey(resourceBundle = BUNDLE) String key, @Nonnull Object... objects) { // return getMessage(key, objects); // } // } // // Path: idea/src/main/java/io/t28/json2java/idea/validator/NullValidator.java // public class NullValidator implements InputValidator { // @Override // public boolean checkInput(@Nullable String text) { // return false; // } // // @Override // public boolean canClose(@Nullable String text) { // return false; // } // } // Path: idea/src/main/java/io/t28/json2java/idea/view/NewClassDialog.java import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; import com.intellij.json.JsonFileType; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.editor.CaretModel; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.EditorFactory; import com.intellij.openapi.editor.EditorSettings; import com.intellij.openapi.editor.colors.EditorColors; import com.intellij.openapi.editor.colors.EditorColorsScheme; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.ui.InputValidator; import com.intellij.openapi.ui.InputValidatorEx; import com.intellij.openapi.ui.ValidationInfo; import io.t28.json2java.idea.Json2JavaBundle; import io.t28.json2java.idea.validator.NullValidator; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jooq.lambda.tuple.Tuple; import javax.annotation.CheckReturnValue; import javax.annotation.Nonnull; import javax.swing.Action; import javax.swing.JComponent; import javax.swing.JPanel; import javax.swing.JTextField; import java.awt.event.ActionEvent; if (isEnabled()) { actionListener.onSettings(NewClassDialog.this); } } } public interface ActionListener { default void onOk(@Nonnull NewClassDialog dialog) { } default void onCancel(@Nonnull NewClassDialog dialog) { } default void onFormat(@Nonnull NewClassDialog dialog) { } default void onSettings(@Nonnull NewClassDialog dialog) { } } public static class Builder { private final Project project; private final Json2JavaBundle bundle; private InputValidator nameValidator; private InputValidator jsonValidator; private ActionListener actionListener; private Builder(@NotNull Project project, @Nonnull Json2JavaBundle bundle) { this.project = project; this.bundle = bundle;
this.nameValidator = new NullValidator();
t28hub/json2java4idea
core/src/test/java/io/t28/json2java/core/json/JsonArrayTest.java
// Path: core/src/test/java/io/t28/json2java/core/Assertions.java // @Nonnull // @CheckReturnValue // public static JsonValueAssert assertThat(@Nullable JsonValue actual) { // return new JsonValueAssert(actual); // }
import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import org.junit.Before; import org.junit.Test; import java.util.Arrays; import java.util.List; import java.util.stream.Stream; import static io.t28.json2java.core.Assertions.assertThat;
/* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.core.json; public class JsonArrayTest { private JsonArray underTest; @Before public void setUp() throws Exception { underTest = new JsonArray(Arrays.asList("foo", "bar", "baz", "qux")); } @Test public void getType() throws Exception { // exercise final TypeName actual = underTest.getType(); // verify
// Path: core/src/test/java/io/t28/json2java/core/Assertions.java // @Nonnull // @CheckReturnValue // public static JsonValueAssert assertThat(@Nullable JsonValue actual) { // return new JsonValueAssert(actual); // } // Path: core/src/test/java/io/t28/json2java/core/json/JsonArrayTest.java import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import org.junit.Before; import org.junit.Test; import java.util.Arrays; import java.util.List; import java.util.stream.Stream; import static io.t28.json2java.core.Assertions.assertThat; /* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.core.json; public class JsonArrayTest { private JsonArray underTest; @Before public void setUp() throws Exception { underTest = new JsonArray(Arrays.asList("foo", "bar", "baz", "qux")); } @Test public void getType() throws Exception { // exercise final TypeName actual = underTest.getType(); // verify
assertThat(actual)
t28hub/json2java4idea
core/src/test/java/io/t28/json2java/core/builder/GsonClassBuilderTest.java
// Path: core/src/main/java/io/t28/json2java/core/naming/DefaultNamePolicy.java // public enum DefaultNamePolicy implements NamePolicy { // CLASS { // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // return format(name, CaseFormat.UPPER_CAMEL); // } // }, // METHOD { // private static final String BOOLEAN_PREFIX = "is"; // private static final String GENERAL_PREFIX = "get"; // // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // final StringBuilder builder = new StringBuilder(); // if (type.equals(TypeName.BOOLEAN) || type.equals(ClassName.get(Boolean.class))) { // builder.append(BOOLEAN_PREFIX); // } else { // builder.append(GENERAL_PREFIX); // } // return builder.append(format(name, CaseFormat.UPPER_CAMEL)) // .toString(); // } // }, // FIELD { // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // return format(name, CaseFormat.LOWER_CAMEL); // } // }, // PARAMETER { // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // return format(name, CaseFormat.LOWER_CAMEL); // } // }; // // private static final String NO_TEXT = ""; // private static final String DELIMITER = "_"; // private static final String DELIMITER_REGEX = "(_|-|\\s|\\.|:)"; // private static final String CAMEL_CASE_REGEX = "(?<!(^|[A-Z]))(?=[A-Z])|(?<!^)(?=[A-Z][a-z])"; // private static final String INVALID_IDENTIFIER_REGEX = "[^A-Za-z0-9_$]"; // // @Nonnull // @CheckReturnValue // public static String format(@Nonnull String name, @Nonnull CaseFormat format) { // final Matcher matcher = Pattern.compile(DELIMITER_REGEX).matcher(name); // final String pattern; // if (matcher.find()) { // pattern = DELIMITER_REGEX; // } else { // pattern = CAMEL_CASE_REGEX; // } // final String snakeCase = Stream.of(name.split(pattern)) // .map(Ascii::toLowerCase) // .map(part -> part.replaceAll(INVALID_IDENTIFIER_REGEX, NO_TEXT)) // .filter(part -> !Strings.isNullOrEmpty(part)) // .collect(Collectors.joining(DELIMITER)); // return CaseFormat.LOWER_UNDERSCORE.to(format, snakeCase); // } // } // // Path: core/src/test/java/io/t28/json2java/core/Assertions.java // @Nonnull // @CheckReturnValue // public static JsonValueAssert assertThat(@Nullable JsonValue actual) { // return new JsonValueAssert(actual); // }
import com.google.gson.annotations.SerializedName; import com.squareup.javapoet.AnnotationSpec; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.TypeName; import io.t28.json2java.core.naming.DefaultNamePolicy; import org.junit.Before; import org.junit.Test; import java.util.List; import static io.t28.json2java.core.Assertions.assertThat;
/* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.core.builder; public class GsonClassBuilderTest { private GsonClassBuilder underTest; @Before public void setUp() throws Exception { underTest = new GsonClassBuilder(
// Path: core/src/main/java/io/t28/json2java/core/naming/DefaultNamePolicy.java // public enum DefaultNamePolicy implements NamePolicy { // CLASS { // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // return format(name, CaseFormat.UPPER_CAMEL); // } // }, // METHOD { // private static final String BOOLEAN_PREFIX = "is"; // private static final String GENERAL_PREFIX = "get"; // // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // final StringBuilder builder = new StringBuilder(); // if (type.equals(TypeName.BOOLEAN) || type.equals(ClassName.get(Boolean.class))) { // builder.append(BOOLEAN_PREFIX); // } else { // builder.append(GENERAL_PREFIX); // } // return builder.append(format(name, CaseFormat.UPPER_CAMEL)) // .toString(); // } // }, // FIELD { // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // return format(name, CaseFormat.LOWER_CAMEL); // } // }, // PARAMETER { // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // return format(name, CaseFormat.LOWER_CAMEL); // } // }; // // private static final String NO_TEXT = ""; // private static final String DELIMITER = "_"; // private static final String DELIMITER_REGEX = "(_|-|\\s|\\.|:)"; // private static final String CAMEL_CASE_REGEX = "(?<!(^|[A-Z]))(?=[A-Z])|(?<!^)(?=[A-Z][a-z])"; // private static final String INVALID_IDENTIFIER_REGEX = "[^A-Za-z0-9_$]"; // // @Nonnull // @CheckReturnValue // public static String format(@Nonnull String name, @Nonnull CaseFormat format) { // final Matcher matcher = Pattern.compile(DELIMITER_REGEX).matcher(name); // final String pattern; // if (matcher.find()) { // pattern = DELIMITER_REGEX; // } else { // pattern = CAMEL_CASE_REGEX; // } // final String snakeCase = Stream.of(name.split(pattern)) // .map(Ascii::toLowerCase) // .map(part -> part.replaceAll(INVALID_IDENTIFIER_REGEX, NO_TEXT)) // .filter(part -> !Strings.isNullOrEmpty(part)) // .collect(Collectors.joining(DELIMITER)); // return CaseFormat.LOWER_UNDERSCORE.to(format, snakeCase); // } // } // // Path: core/src/test/java/io/t28/json2java/core/Assertions.java // @Nonnull // @CheckReturnValue // public static JsonValueAssert assertThat(@Nullable JsonValue actual) { // return new JsonValueAssert(actual); // } // Path: core/src/test/java/io/t28/json2java/core/builder/GsonClassBuilderTest.java import com.google.gson.annotations.SerializedName; import com.squareup.javapoet.AnnotationSpec; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.TypeName; import io.t28.json2java.core.naming.DefaultNamePolicy; import org.junit.Before; import org.junit.Test; import java.util.List; import static io.t28.json2java.core.Assertions.assertThat; /* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.core.builder; public class GsonClassBuilderTest { private GsonClassBuilder underTest; @Before public void setUp() throws Exception { underTest = new GsonClassBuilder(
DefaultNamePolicy.FIELD,
t28hub/json2java4idea
core/src/test/java/io/t28/json2java/core/builder/GsonClassBuilderTest.java
// Path: core/src/main/java/io/t28/json2java/core/naming/DefaultNamePolicy.java // public enum DefaultNamePolicy implements NamePolicy { // CLASS { // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // return format(name, CaseFormat.UPPER_CAMEL); // } // }, // METHOD { // private static final String BOOLEAN_PREFIX = "is"; // private static final String GENERAL_PREFIX = "get"; // // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // final StringBuilder builder = new StringBuilder(); // if (type.equals(TypeName.BOOLEAN) || type.equals(ClassName.get(Boolean.class))) { // builder.append(BOOLEAN_PREFIX); // } else { // builder.append(GENERAL_PREFIX); // } // return builder.append(format(name, CaseFormat.UPPER_CAMEL)) // .toString(); // } // }, // FIELD { // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // return format(name, CaseFormat.LOWER_CAMEL); // } // }, // PARAMETER { // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // return format(name, CaseFormat.LOWER_CAMEL); // } // }; // // private static final String NO_TEXT = ""; // private static final String DELIMITER = "_"; // private static final String DELIMITER_REGEX = "(_|-|\\s|\\.|:)"; // private static final String CAMEL_CASE_REGEX = "(?<!(^|[A-Z]))(?=[A-Z])|(?<!^)(?=[A-Z][a-z])"; // private static final String INVALID_IDENTIFIER_REGEX = "[^A-Za-z0-9_$]"; // // @Nonnull // @CheckReturnValue // public static String format(@Nonnull String name, @Nonnull CaseFormat format) { // final Matcher matcher = Pattern.compile(DELIMITER_REGEX).matcher(name); // final String pattern; // if (matcher.find()) { // pattern = DELIMITER_REGEX; // } else { // pattern = CAMEL_CASE_REGEX; // } // final String snakeCase = Stream.of(name.split(pattern)) // .map(Ascii::toLowerCase) // .map(part -> part.replaceAll(INVALID_IDENTIFIER_REGEX, NO_TEXT)) // .filter(part -> !Strings.isNullOrEmpty(part)) // .collect(Collectors.joining(DELIMITER)); // return CaseFormat.LOWER_UNDERSCORE.to(format, snakeCase); // } // } // // Path: core/src/test/java/io/t28/json2java/core/Assertions.java // @Nonnull // @CheckReturnValue // public static JsonValueAssert assertThat(@Nullable JsonValue actual) { // return new JsonValueAssert(actual); // }
import com.google.gson.annotations.SerializedName; import com.squareup.javapoet.AnnotationSpec; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.TypeName; import io.t28.json2java.core.naming.DefaultNamePolicy; import org.junit.Before; import org.junit.Test; import java.util.List; import static io.t28.json2java.core.Assertions.assertThat;
/* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.core.builder; public class GsonClassBuilderTest { private GsonClassBuilder underTest; @Before public void setUp() throws Exception { underTest = new GsonClassBuilder( DefaultNamePolicy.FIELD, DefaultNamePolicy.METHOD, DefaultNamePolicy.PARAMETER ); } @Test public void buildFields() throws Exception { // setup underTest.addProperty("foo", TypeName.INT) .addProperty("bar", TypeName.OBJECT) .addProperty("baz", TypeName.BOOLEAN); // exercise final List<FieldSpec> actual = underTest.buildFields(); // verify
// Path: core/src/main/java/io/t28/json2java/core/naming/DefaultNamePolicy.java // public enum DefaultNamePolicy implements NamePolicy { // CLASS { // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // return format(name, CaseFormat.UPPER_CAMEL); // } // }, // METHOD { // private static final String BOOLEAN_PREFIX = "is"; // private static final String GENERAL_PREFIX = "get"; // // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // final StringBuilder builder = new StringBuilder(); // if (type.equals(TypeName.BOOLEAN) || type.equals(ClassName.get(Boolean.class))) { // builder.append(BOOLEAN_PREFIX); // } else { // builder.append(GENERAL_PREFIX); // } // return builder.append(format(name, CaseFormat.UPPER_CAMEL)) // .toString(); // } // }, // FIELD { // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // return format(name, CaseFormat.LOWER_CAMEL); // } // }, // PARAMETER { // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // return format(name, CaseFormat.LOWER_CAMEL); // } // }; // // private static final String NO_TEXT = ""; // private static final String DELIMITER = "_"; // private static final String DELIMITER_REGEX = "(_|-|\\s|\\.|:)"; // private static final String CAMEL_CASE_REGEX = "(?<!(^|[A-Z]))(?=[A-Z])|(?<!^)(?=[A-Z][a-z])"; // private static final String INVALID_IDENTIFIER_REGEX = "[^A-Za-z0-9_$]"; // // @Nonnull // @CheckReturnValue // public static String format(@Nonnull String name, @Nonnull CaseFormat format) { // final Matcher matcher = Pattern.compile(DELIMITER_REGEX).matcher(name); // final String pattern; // if (matcher.find()) { // pattern = DELIMITER_REGEX; // } else { // pattern = CAMEL_CASE_REGEX; // } // final String snakeCase = Stream.of(name.split(pattern)) // .map(Ascii::toLowerCase) // .map(part -> part.replaceAll(INVALID_IDENTIFIER_REGEX, NO_TEXT)) // .filter(part -> !Strings.isNullOrEmpty(part)) // .collect(Collectors.joining(DELIMITER)); // return CaseFormat.LOWER_UNDERSCORE.to(format, snakeCase); // } // } // // Path: core/src/test/java/io/t28/json2java/core/Assertions.java // @Nonnull // @CheckReturnValue // public static JsonValueAssert assertThat(@Nullable JsonValue actual) { // return new JsonValueAssert(actual); // } // Path: core/src/test/java/io/t28/json2java/core/builder/GsonClassBuilderTest.java import com.google.gson.annotations.SerializedName; import com.squareup.javapoet.AnnotationSpec; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.TypeName; import io.t28.json2java.core.naming.DefaultNamePolicy; import org.junit.Before; import org.junit.Test; import java.util.List; import static io.t28.json2java.core.Assertions.assertThat; /* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.core.builder; public class GsonClassBuilderTest { private GsonClassBuilder underTest; @Before public void setUp() throws Exception { underTest = new GsonClassBuilder( DefaultNamePolicy.FIELD, DefaultNamePolicy.METHOD, DefaultNamePolicy.PARAMETER ); } @Test public void buildFields() throws Exception { // setup underTest.addProperty("foo", TypeName.INT) .addProperty("bar", TypeName.OBJECT) .addProperty("baz", TypeName.BOOLEAN); // exercise final List<FieldSpec> actual = underTest.buildFields(); // verify
assertThat(actual)
t28hub/json2java4idea
core/src/main/java/io/t28/json2java/core/io/JsonParserImpl.java
// Path: core/src/main/java/io/t28/json2java/core/io/exception/JsonParseException.java // public class JsonParseException extends IOException { // private static final long serialVersionUID = 1477109671450199015L; // // public JsonParseException(@Nonnull String message, @Nonnull Throwable cause) { // super(message, cause); // } // } // // Path: core/src/main/java/io/t28/json2java/core/json/JsonValue.java // public abstract class JsonValue { // @Nonnull // @CheckReturnValue // public static JsonValue wrap(@Nullable Object value) { // return Stream.of(ValueType.values()) // .filter(type -> type.isAcceptable(value)) // .findFirst() // .orElseThrow(() -> new IllegalArgumentException("Unsupported type of value(" + value + ")")) // .wrap(value); // } // // @Nonnull // public abstract TypeName getType(); // // public abstract Object getValue(); // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("type", getType()) // .add("value", getValue()) // .toString(); // } // // @CheckReturnValue // public boolean isNull() { // return this instanceof JsonNull; // } // // @CheckReturnValue // public boolean isBoolean() { // return this instanceof JsonBoolean; // } // // @CheckReturnValue // public boolean isNumber() { // return this instanceof JsonNumber; // } // // @CheckReturnValue // public boolean isString() { // return this instanceof JsonString; // } // // @CheckReturnValue // public boolean isArray() { // return this instanceof JsonArray; // } // // @CheckReturnValue // public boolean isObject() { // return this instanceof JsonObject; // } // // @Nonnull // @CheckReturnValue // public JsonNull asNull() { // if (isNull()) { // return (JsonNull) this; // } // throw new IllegalStateException("This value is not a null"); // } // // @Nonnull // @CheckReturnValue // public JsonBoolean asBoolean() { // if (isBoolean()) { // return (JsonBoolean) this; // } // throw new IllegalStateException("This value is not a boolean"); // } // // @Nonnull // @CheckReturnValue // public JsonNumber asNumber() { // if (isNumber()) { // return (JsonNumber) this; // } // throw new IllegalStateException("This value is not a number"); // } // // @Nonnull // @CheckReturnValue // public JsonString asString() { // if (isString()) { // return (JsonString) this; // } // throw new IllegalStateException("This value is not a string"); // } // // @Nonnull // @CheckReturnValue // public JsonArray asArray() { // if (isArray()) { // return (JsonArray) this; // } // throw new IllegalStateException("This value is not an array"); // } // // @Nonnull // @CheckReturnValue // public JsonObject asObject() { // if (isObject()) { // return (JsonObject) this; // } // throw new IllegalStateException("This value is not an object"); // } // }
import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.annotations.VisibleForTesting; import io.t28.json2java.core.io.exception.JsonParseException; import io.t28.json2java.core.json.JsonValue; import javax.annotation.Nonnull; import java.io.IOException;
/* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.core.io; public class JsonParserImpl implements JsonParser { private final ObjectMapper mapper; public JsonParserImpl() { this(new ObjectMapper()); } @VisibleForTesting JsonParserImpl(@Nonnull ObjectMapper mapper) { this.mapper = mapper; } @Nonnull @Override
// Path: core/src/main/java/io/t28/json2java/core/io/exception/JsonParseException.java // public class JsonParseException extends IOException { // private static final long serialVersionUID = 1477109671450199015L; // // public JsonParseException(@Nonnull String message, @Nonnull Throwable cause) { // super(message, cause); // } // } // // Path: core/src/main/java/io/t28/json2java/core/json/JsonValue.java // public abstract class JsonValue { // @Nonnull // @CheckReturnValue // public static JsonValue wrap(@Nullable Object value) { // return Stream.of(ValueType.values()) // .filter(type -> type.isAcceptable(value)) // .findFirst() // .orElseThrow(() -> new IllegalArgumentException("Unsupported type of value(" + value + ")")) // .wrap(value); // } // // @Nonnull // public abstract TypeName getType(); // // public abstract Object getValue(); // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("type", getType()) // .add("value", getValue()) // .toString(); // } // // @CheckReturnValue // public boolean isNull() { // return this instanceof JsonNull; // } // // @CheckReturnValue // public boolean isBoolean() { // return this instanceof JsonBoolean; // } // // @CheckReturnValue // public boolean isNumber() { // return this instanceof JsonNumber; // } // // @CheckReturnValue // public boolean isString() { // return this instanceof JsonString; // } // // @CheckReturnValue // public boolean isArray() { // return this instanceof JsonArray; // } // // @CheckReturnValue // public boolean isObject() { // return this instanceof JsonObject; // } // // @Nonnull // @CheckReturnValue // public JsonNull asNull() { // if (isNull()) { // return (JsonNull) this; // } // throw new IllegalStateException("This value is not a null"); // } // // @Nonnull // @CheckReturnValue // public JsonBoolean asBoolean() { // if (isBoolean()) { // return (JsonBoolean) this; // } // throw new IllegalStateException("This value is not a boolean"); // } // // @Nonnull // @CheckReturnValue // public JsonNumber asNumber() { // if (isNumber()) { // return (JsonNumber) this; // } // throw new IllegalStateException("This value is not a number"); // } // // @Nonnull // @CheckReturnValue // public JsonString asString() { // if (isString()) { // return (JsonString) this; // } // throw new IllegalStateException("This value is not a string"); // } // // @Nonnull // @CheckReturnValue // public JsonArray asArray() { // if (isArray()) { // return (JsonArray) this; // } // throw new IllegalStateException("This value is not an array"); // } // // @Nonnull // @CheckReturnValue // public JsonObject asObject() { // if (isObject()) { // return (JsonObject) this; // } // throw new IllegalStateException("This value is not an object"); // } // } // Path: core/src/main/java/io/t28/json2java/core/io/JsonParserImpl.java import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.annotations.VisibleForTesting; import io.t28.json2java.core.io.exception.JsonParseException; import io.t28.json2java.core.json.JsonValue; import javax.annotation.Nonnull; import java.io.IOException; /* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.core.io; public class JsonParserImpl implements JsonParser { private final ObjectMapper mapper; public JsonParserImpl() { this(new ObjectMapper()); } @VisibleForTesting JsonParserImpl(@Nonnull ObjectMapper mapper) { this.mapper = mapper; } @Nonnull @Override
public JsonValue parse(@Nonnull String json) throws JsonParseException {
t28hub/json2java4idea
core/src/main/java/io/t28/json2java/core/io/JsonParserImpl.java
// Path: core/src/main/java/io/t28/json2java/core/io/exception/JsonParseException.java // public class JsonParseException extends IOException { // private static final long serialVersionUID = 1477109671450199015L; // // public JsonParseException(@Nonnull String message, @Nonnull Throwable cause) { // super(message, cause); // } // } // // Path: core/src/main/java/io/t28/json2java/core/json/JsonValue.java // public abstract class JsonValue { // @Nonnull // @CheckReturnValue // public static JsonValue wrap(@Nullable Object value) { // return Stream.of(ValueType.values()) // .filter(type -> type.isAcceptable(value)) // .findFirst() // .orElseThrow(() -> new IllegalArgumentException("Unsupported type of value(" + value + ")")) // .wrap(value); // } // // @Nonnull // public abstract TypeName getType(); // // public abstract Object getValue(); // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("type", getType()) // .add("value", getValue()) // .toString(); // } // // @CheckReturnValue // public boolean isNull() { // return this instanceof JsonNull; // } // // @CheckReturnValue // public boolean isBoolean() { // return this instanceof JsonBoolean; // } // // @CheckReturnValue // public boolean isNumber() { // return this instanceof JsonNumber; // } // // @CheckReturnValue // public boolean isString() { // return this instanceof JsonString; // } // // @CheckReturnValue // public boolean isArray() { // return this instanceof JsonArray; // } // // @CheckReturnValue // public boolean isObject() { // return this instanceof JsonObject; // } // // @Nonnull // @CheckReturnValue // public JsonNull asNull() { // if (isNull()) { // return (JsonNull) this; // } // throw new IllegalStateException("This value is not a null"); // } // // @Nonnull // @CheckReturnValue // public JsonBoolean asBoolean() { // if (isBoolean()) { // return (JsonBoolean) this; // } // throw new IllegalStateException("This value is not a boolean"); // } // // @Nonnull // @CheckReturnValue // public JsonNumber asNumber() { // if (isNumber()) { // return (JsonNumber) this; // } // throw new IllegalStateException("This value is not a number"); // } // // @Nonnull // @CheckReturnValue // public JsonString asString() { // if (isString()) { // return (JsonString) this; // } // throw new IllegalStateException("This value is not a string"); // } // // @Nonnull // @CheckReturnValue // public JsonArray asArray() { // if (isArray()) { // return (JsonArray) this; // } // throw new IllegalStateException("This value is not an array"); // } // // @Nonnull // @CheckReturnValue // public JsonObject asObject() { // if (isObject()) { // return (JsonObject) this; // } // throw new IllegalStateException("This value is not an object"); // } // }
import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.annotations.VisibleForTesting; import io.t28.json2java.core.io.exception.JsonParseException; import io.t28.json2java.core.json.JsonValue; import javax.annotation.Nonnull; import java.io.IOException;
/* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.core.io; public class JsonParserImpl implements JsonParser { private final ObjectMapper mapper; public JsonParserImpl() { this(new ObjectMapper()); } @VisibleForTesting JsonParserImpl(@Nonnull ObjectMapper mapper) { this.mapper = mapper; } @Nonnull @Override
// Path: core/src/main/java/io/t28/json2java/core/io/exception/JsonParseException.java // public class JsonParseException extends IOException { // private static final long serialVersionUID = 1477109671450199015L; // // public JsonParseException(@Nonnull String message, @Nonnull Throwable cause) { // super(message, cause); // } // } // // Path: core/src/main/java/io/t28/json2java/core/json/JsonValue.java // public abstract class JsonValue { // @Nonnull // @CheckReturnValue // public static JsonValue wrap(@Nullable Object value) { // return Stream.of(ValueType.values()) // .filter(type -> type.isAcceptable(value)) // .findFirst() // .orElseThrow(() -> new IllegalArgumentException("Unsupported type of value(" + value + ")")) // .wrap(value); // } // // @Nonnull // public abstract TypeName getType(); // // public abstract Object getValue(); // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("type", getType()) // .add("value", getValue()) // .toString(); // } // // @CheckReturnValue // public boolean isNull() { // return this instanceof JsonNull; // } // // @CheckReturnValue // public boolean isBoolean() { // return this instanceof JsonBoolean; // } // // @CheckReturnValue // public boolean isNumber() { // return this instanceof JsonNumber; // } // // @CheckReturnValue // public boolean isString() { // return this instanceof JsonString; // } // // @CheckReturnValue // public boolean isArray() { // return this instanceof JsonArray; // } // // @CheckReturnValue // public boolean isObject() { // return this instanceof JsonObject; // } // // @Nonnull // @CheckReturnValue // public JsonNull asNull() { // if (isNull()) { // return (JsonNull) this; // } // throw new IllegalStateException("This value is not a null"); // } // // @Nonnull // @CheckReturnValue // public JsonBoolean asBoolean() { // if (isBoolean()) { // return (JsonBoolean) this; // } // throw new IllegalStateException("This value is not a boolean"); // } // // @Nonnull // @CheckReturnValue // public JsonNumber asNumber() { // if (isNumber()) { // return (JsonNumber) this; // } // throw new IllegalStateException("This value is not a number"); // } // // @Nonnull // @CheckReturnValue // public JsonString asString() { // if (isString()) { // return (JsonString) this; // } // throw new IllegalStateException("This value is not a string"); // } // // @Nonnull // @CheckReturnValue // public JsonArray asArray() { // if (isArray()) { // return (JsonArray) this; // } // throw new IllegalStateException("This value is not an array"); // } // // @Nonnull // @CheckReturnValue // public JsonObject asObject() { // if (isObject()) { // return (JsonObject) this; // } // throw new IllegalStateException("This value is not an object"); // } // } // Path: core/src/main/java/io/t28/json2java/core/io/JsonParserImpl.java import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.annotations.VisibleForTesting; import io.t28.json2java.core.io.exception.JsonParseException; import io.t28.json2java.core.json.JsonValue; import javax.annotation.Nonnull; import java.io.IOException; /* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.core.io; public class JsonParserImpl implements JsonParser { private final ObjectMapper mapper; public JsonParserImpl() { this(new ObjectMapper()); } @VisibleForTesting JsonParserImpl(@Nonnull ObjectMapper mapper) { this.mapper = mapper; } @Nonnull @Override
public JsonValue parse(@Nonnull String json) throws JsonParseException {
t28hub/json2java4idea
core/src/test/java/io/t28/json2java/core/builder/ModelClassBuilderTest.java
// Path: core/src/main/java/io/t28/json2java/core/naming/DefaultNamePolicy.java // public enum DefaultNamePolicy implements NamePolicy { // CLASS { // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // return format(name, CaseFormat.UPPER_CAMEL); // } // }, // METHOD { // private static final String BOOLEAN_PREFIX = "is"; // private static final String GENERAL_PREFIX = "get"; // // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // final StringBuilder builder = new StringBuilder(); // if (type.equals(TypeName.BOOLEAN) || type.equals(ClassName.get(Boolean.class))) { // builder.append(BOOLEAN_PREFIX); // } else { // builder.append(GENERAL_PREFIX); // } // return builder.append(format(name, CaseFormat.UPPER_CAMEL)) // .toString(); // } // }, // FIELD { // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // return format(name, CaseFormat.LOWER_CAMEL); // } // }, // PARAMETER { // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // return format(name, CaseFormat.LOWER_CAMEL); // } // }; // // private static final String NO_TEXT = ""; // private static final String DELIMITER = "_"; // private static final String DELIMITER_REGEX = "(_|-|\\s|\\.|:)"; // private static final String CAMEL_CASE_REGEX = "(?<!(^|[A-Z]))(?=[A-Z])|(?<!^)(?=[A-Z][a-z])"; // private static final String INVALID_IDENTIFIER_REGEX = "[^A-Za-z0-9_$]"; // // @Nonnull // @CheckReturnValue // public static String format(@Nonnull String name, @Nonnull CaseFormat format) { // final Matcher matcher = Pattern.compile(DELIMITER_REGEX).matcher(name); // final String pattern; // if (matcher.find()) { // pattern = DELIMITER_REGEX; // } else { // pattern = CAMEL_CASE_REGEX; // } // final String snakeCase = Stream.of(name.split(pattern)) // .map(Ascii::toLowerCase) // .map(part -> part.replaceAll(INVALID_IDENTIFIER_REGEX, NO_TEXT)) // .filter(part -> !Strings.isNullOrEmpty(part)) // .collect(Collectors.joining(DELIMITER)); // return CaseFormat.LOWER_UNDERSCORE.to(format, snakeCase); // } // } // // Path: core/src/test/java/io/t28/json2java/core/Assertions.java // @Nonnull // @CheckReturnValue // public static JsonValueAssert assertThat(@Nullable JsonValue actual) { // return new JsonValueAssert(actual); // }
import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.TypeName; import io.t28.json2java.core.naming.DefaultNamePolicy; import org.junit.Before; import org.junit.Test; import javax.lang.model.element.Modifier; import java.util.List; import static io.t28.json2java.core.Assertions.assertThat;
/* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.core.builder; public class ModelClassBuilderTest { private ModelClassBuilder underTest; @Before public void setUp() throws Exception { underTest = new ModelClassBuilder(
// Path: core/src/main/java/io/t28/json2java/core/naming/DefaultNamePolicy.java // public enum DefaultNamePolicy implements NamePolicy { // CLASS { // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // return format(name, CaseFormat.UPPER_CAMEL); // } // }, // METHOD { // private static final String BOOLEAN_PREFIX = "is"; // private static final String GENERAL_PREFIX = "get"; // // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // final StringBuilder builder = new StringBuilder(); // if (type.equals(TypeName.BOOLEAN) || type.equals(ClassName.get(Boolean.class))) { // builder.append(BOOLEAN_PREFIX); // } else { // builder.append(GENERAL_PREFIX); // } // return builder.append(format(name, CaseFormat.UPPER_CAMEL)) // .toString(); // } // }, // FIELD { // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // return format(name, CaseFormat.LOWER_CAMEL); // } // }, // PARAMETER { // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // return format(name, CaseFormat.LOWER_CAMEL); // } // }; // // private static final String NO_TEXT = ""; // private static final String DELIMITER = "_"; // private static final String DELIMITER_REGEX = "(_|-|\\s|\\.|:)"; // private static final String CAMEL_CASE_REGEX = "(?<!(^|[A-Z]))(?=[A-Z])|(?<!^)(?=[A-Z][a-z])"; // private static final String INVALID_IDENTIFIER_REGEX = "[^A-Za-z0-9_$]"; // // @Nonnull // @CheckReturnValue // public static String format(@Nonnull String name, @Nonnull CaseFormat format) { // final Matcher matcher = Pattern.compile(DELIMITER_REGEX).matcher(name); // final String pattern; // if (matcher.find()) { // pattern = DELIMITER_REGEX; // } else { // pattern = CAMEL_CASE_REGEX; // } // final String snakeCase = Stream.of(name.split(pattern)) // .map(Ascii::toLowerCase) // .map(part -> part.replaceAll(INVALID_IDENTIFIER_REGEX, NO_TEXT)) // .filter(part -> !Strings.isNullOrEmpty(part)) // .collect(Collectors.joining(DELIMITER)); // return CaseFormat.LOWER_UNDERSCORE.to(format, snakeCase); // } // } // // Path: core/src/test/java/io/t28/json2java/core/Assertions.java // @Nonnull // @CheckReturnValue // public static JsonValueAssert assertThat(@Nullable JsonValue actual) { // return new JsonValueAssert(actual); // } // Path: core/src/test/java/io/t28/json2java/core/builder/ModelClassBuilderTest.java import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.TypeName; import io.t28.json2java.core.naming.DefaultNamePolicy; import org.junit.Before; import org.junit.Test; import javax.lang.model.element.Modifier; import java.util.List; import static io.t28.json2java.core.Assertions.assertThat; /* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.core.builder; public class ModelClassBuilderTest { private ModelClassBuilder underTest; @Before public void setUp() throws Exception { underTest = new ModelClassBuilder(
DefaultNamePolicy.FIELD,
t28hub/json2java4idea
core/src/test/java/io/t28/json2java/core/builder/ModelClassBuilderTest.java
// Path: core/src/main/java/io/t28/json2java/core/naming/DefaultNamePolicy.java // public enum DefaultNamePolicy implements NamePolicy { // CLASS { // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // return format(name, CaseFormat.UPPER_CAMEL); // } // }, // METHOD { // private static final String BOOLEAN_PREFIX = "is"; // private static final String GENERAL_PREFIX = "get"; // // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // final StringBuilder builder = new StringBuilder(); // if (type.equals(TypeName.BOOLEAN) || type.equals(ClassName.get(Boolean.class))) { // builder.append(BOOLEAN_PREFIX); // } else { // builder.append(GENERAL_PREFIX); // } // return builder.append(format(name, CaseFormat.UPPER_CAMEL)) // .toString(); // } // }, // FIELD { // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // return format(name, CaseFormat.LOWER_CAMEL); // } // }, // PARAMETER { // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // return format(name, CaseFormat.LOWER_CAMEL); // } // }; // // private static final String NO_TEXT = ""; // private static final String DELIMITER = "_"; // private static final String DELIMITER_REGEX = "(_|-|\\s|\\.|:)"; // private static final String CAMEL_CASE_REGEX = "(?<!(^|[A-Z]))(?=[A-Z])|(?<!^)(?=[A-Z][a-z])"; // private static final String INVALID_IDENTIFIER_REGEX = "[^A-Za-z0-9_$]"; // // @Nonnull // @CheckReturnValue // public static String format(@Nonnull String name, @Nonnull CaseFormat format) { // final Matcher matcher = Pattern.compile(DELIMITER_REGEX).matcher(name); // final String pattern; // if (matcher.find()) { // pattern = DELIMITER_REGEX; // } else { // pattern = CAMEL_CASE_REGEX; // } // final String snakeCase = Stream.of(name.split(pattern)) // .map(Ascii::toLowerCase) // .map(part -> part.replaceAll(INVALID_IDENTIFIER_REGEX, NO_TEXT)) // .filter(part -> !Strings.isNullOrEmpty(part)) // .collect(Collectors.joining(DELIMITER)); // return CaseFormat.LOWER_UNDERSCORE.to(format, snakeCase); // } // } // // Path: core/src/test/java/io/t28/json2java/core/Assertions.java // @Nonnull // @CheckReturnValue // public static JsonValueAssert assertThat(@Nullable JsonValue actual) { // return new JsonValueAssert(actual); // }
import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.TypeName; import io.t28.json2java.core.naming.DefaultNamePolicy; import org.junit.Before; import org.junit.Test; import javax.lang.model.element.Modifier; import java.util.List; import static io.t28.json2java.core.Assertions.assertThat;
/* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.core.builder; public class ModelClassBuilderTest { private ModelClassBuilder underTest; @Before public void setUp() throws Exception { underTest = new ModelClassBuilder( DefaultNamePolicy.FIELD, DefaultNamePolicy.METHOD, DefaultNamePolicy.PARAMETER ); } @Test public void buildFields() throws Exception { // setup underTest.addProperty("foo", TypeName.INT) .addProperty("bar", TypeName.OBJECT) .addProperty("baz", TypeName.BOOLEAN); // exercise final List<FieldSpec> actual = underTest.buildFields(); // verify
// Path: core/src/main/java/io/t28/json2java/core/naming/DefaultNamePolicy.java // public enum DefaultNamePolicy implements NamePolicy { // CLASS { // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // return format(name, CaseFormat.UPPER_CAMEL); // } // }, // METHOD { // private static final String BOOLEAN_PREFIX = "is"; // private static final String GENERAL_PREFIX = "get"; // // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // final StringBuilder builder = new StringBuilder(); // if (type.equals(TypeName.BOOLEAN) || type.equals(ClassName.get(Boolean.class))) { // builder.append(BOOLEAN_PREFIX); // } else { // builder.append(GENERAL_PREFIX); // } // return builder.append(format(name, CaseFormat.UPPER_CAMEL)) // .toString(); // } // }, // FIELD { // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // return format(name, CaseFormat.LOWER_CAMEL); // } // }, // PARAMETER { // @Nonnull // @Override // public String convert(@Nonnull String name, @Nonnull TypeName type) { // return format(name, CaseFormat.LOWER_CAMEL); // } // }; // // private static final String NO_TEXT = ""; // private static final String DELIMITER = "_"; // private static final String DELIMITER_REGEX = "(_|-|\\s|\\.|:)"; // private static final String CAMEL_CASE_REGEX = "(?<!(^|[A-Z]))(?=[A-Z])|(?<!^)(?=[A-Z][a-z])"; // private static final String INVALID_IDENTIFIER_REGEX = "[^A-Za-z0-9_$]"; // // @Nonnull // @CheckReturnValue // public static String format(@Nonnull String name, @Nonnull CaseFormat format) { // final Matcher matcher = Pattern.compile(DELIMITER_REGEX).matcher(name); // final String pattern; // if (matcher.find()) { // pattern = DELIMITER_REGEX; // } else { // pattern = CAMEL_CASE_REGEX; // } // final String snakeCase = Stream.of(name.split(pattern)) // .map(Ascii::toLowerCase) // .map(part -> part.replaceAll(INVALID_IDENTIFIER_REGEX, NO_TEXT)) // .filter(part -> !Strings.isNullOrEmpty(part)) // .collect(Collectors.joining(DELIMITER)); // return CaseFormat.LOWER_UNDERSCORE.to(format, snakeCase); // } // } // // Path: core/src/test/java/io/t28/json2java/core/Assertions.java // @Nonnull // @CheckReturnValue // public static JsonValueAssert assertThat(@Nullable JsonValue actual) { // return new JsonValueAssert(actual); // } // Path: core/src/test/java/io/t28/json2java/core/builder/ModelClassBuilderTest.java import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.TypeName; import io.t28.json2java.core.naming.DefaultNamePolicy; import org.junit.Before; import org.junit.Test; import javax.lang.model.element.Modifier; import java.util.List; import static io.t28.json2java.core.Assertions.assertThat; /* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.core.builder; public class ModelClassBuilderTest { private ModelClassBuilder underTest; @Before public void setUp() throws Exception { underTest = new ModelClassBuilder( DefaultNamePolicy.FIELD, DefaultNamePolicy.METHOD, DefaultNamePolicy.PARAMETER ); } @Test public void buildFields() throws Exception { // setup underTest.addProperty("foo", TypeName.INT) .addProperty("bar", TypeName.OBJECT) .addProperty("baz", TypeName.BOOLEAN); // exercise final List<FieldSpec> actual = underTest.buildFields(); // verify
assertThat(actual)
t28hub/json2java4idea
core/src/main/java/io/t28/json2java/core/builder/ClassBuilder.java
// Path: core/src/main/java/io/t28/json2java/core/naming/NamePolicy.java // public interface NamePolicy { // @Nonnull // @CheckReturnValue // String convert(@Nonnull String name, @Nonnull TypeName type); // }
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.squareup.javapoet.AnnotationSpec; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import io.t28.json2java.core.naming.NamePolicy; import javax.annotation.CheckReturnValue; import javax.annotation.Nonnull; import javax.lang.model.element.Modifier; import java.util.Collections; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set;
/* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.core.builder; @SuppressWarnings("WeakerAccess") public abstract class ClassBuilder {
// Path: core/src/main/java/io/t28/json2java/core/naming/NamePolicy.java // public interface NamePolicy { // @Nonnull // @CheckReturnValue // String convert(@Nonnull String name, @Nonnull TypeName type); // } // Path: core/src/main/java/io/t28/json2java/core/builder/ClassBuilder.java import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.squareup.javapoet.AnnotationSpec; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import io.t28.json2java.core.naming.NamePolicy; import javax.annotation.CheckReturnValue; import javax.annotation.Nonnull; import javax.lang.model.element.Modifier; import java.util.Collections; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; /* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.core.builder; @SuppressWarnings("WeakerAccess") public abstract class ClassBuilder {
protected final NamePolicy fieldNamePolicy;
t28hub/json2java4idea
idea/src/test/java/io/t28/json2java/idea/validator/ClassPrefixValidatorTest.java
// Path: idea/src/test/java/io/t28/json2java/idea/IdeaProjectTest.java // public class IdeaProjectTest { // private JavaCodeInsightTestFixture fixture; // // @Before // public void setUp() throws Exception { // final IdeaTestFixtureFactory ideaFixtureFactory = IdeaTestFixtureFactory.getFixtureFactory(); // final JavaTestFixtureFactory javaFixtureFactory = JavaTestFixtureFactory.getFixtureFactory(); // final TestFixtureBuilder<IdeaProjectTestFixture> fixtureBuilder = ideaFixtureFactory.createLightFixtureBuilder(); // fixture = javaFixtureFactory.createCodeInsightFixture(fixtureBuilder.getFixture()); // fixture.setUp(); // } // // @After // public void tearDown() throws Exception { // fixture.tearDown(); // } // // @Nonnull // @CheckReturnValue // protected Application getApplication() { // if (fixture == null) { // throw new AssertionError("getApplication() must call after setUp()"); // } // return ApplicationManager.getApplication(); // } // // @Nonnull // @CheckReturnValue // protected Project getProject() { // if (fixture == null) { // throw new AssertionError("getProject() must call after setUp()"); // } // return fixture.getProject(); // } // } // // Path: idea/src/main/java/io/t28/json2java/idea/Json2JavaBundle.java // public class Json2JavaBundle extends AbstractBundle { // private static final String BUNDLE = "messages.Json2Java4IdeaBundle"; // // public Json2JavaBundle() { // super(BUNDLE); // } // // @Nonnull // public static Json2JavaBundle getInstance() { // return new Json2JavaBundle(); // } // // @Nonnull // @CheckReturnValue // public String message(@Nonnull @PropertyKey(resourceBundle = BUNDLE) String key, @Nonnull Object... objects) { // return getMessage(key, objects); // } // }
import com.intellij.openapi.project.Project; import com.intellij.psi.PsiNameHelper; import io.t28.json2java.idea.IdeaProjectTest; import io.t28.json2java.idea.Json2JavaBundle; import org.junit.Before; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat;
/* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.idea.validator; public class ClassPrefixValidatorTest extends IdeaProjectTest { private ClassPrefixValidator underTest; @Before @Override public void setUp() throws Exception { super.setUp(); final Project project = getProject();
// Path: idea/src/test/java/io/t28/json2java/idea/IdeaProjectTest.java // public class IdeaProjectTest { // private JavaCodeInsightTestFixture fixture; // // @Before // public void setUp() throws Exception { // final IdeaTestFixtureFactory ideaFixtureFactory = IdeaTestFixtureFactory.getFixtureFactory(); // final JavaTestFixtureFactory javaFixtureFactory = JavaTestFixtureFactory.getFixtureFactory(); // final TestFixtureBuilder<IdeaProjectTestFixture> fixtureBuilder = ideaFixtureFactory.createLightFixtureBuilder(); // fixture = javaFixtureFactory.createCodeInsightFixture(fixtureBuilder.getFixture()); // fixture.setUp(); // } // // @After // public void tearDown() throws Exception { // fixture.tearDown(); // } // // @Nonnull // @CheckReturnValue // protected Application getApplication() { // if (fixture == null) { // throw new AssertionError("getApplication() must call after setUp()"); // } // return ApplicationManager.getApplication(); // } // // @Nonnull // @CheckReturnValue // protected Project getProject() { // if (fixture == null) { // throw new AssertionError("getProject() must call after setUp()"); // } // return fixture.getProject(); // } // } // // Path: idea/src/main/java/io/t28/json2java/idea/Json2JavaBundle.java // public class Json2JavaBundle extends AbstractBundle { // private static final String BUNDLE = "messages.Json2Java4IdeaBundle"; // // public Json2JavaBundle() { // super(BUNDLE); // } // // @Nonnull // public static Json2JavaBundle getInstance() { // return new Json2JavaBundle(); // } // // @Nonnull // @CheckReturnValue // public String message(@Nonnull @PropertyKey(resourceBundle = BUNDLE) String key, @Nonnull Object... objects) { // return getMessage(key, objects); // } // } // Path: idea/src/test/java/io/t28/json2java/idea/validator/ClassPrefixValidatorTest.java import com.intellij.openapi.project.Project; import com.intellij.psi.PsiNameHelper; import io.t28.json2java.idea.IdeaProjectTest; import io.t28.json2java.idea.Json2JavaBundle; import org.junit.Before; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; /* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.idea.validator; public class ClassPrefixValidatorTest extends IdeaProjectTest { private ClassPrefixValidator underTest; @Before @Override public void setUp() throws Exception { super.setUp(); final Project project = getProject();
final Json2JavaBundle bundle = Json2JavaBundle.getInstance();
t28hub/json2java4idea
idea/src/test/java/io/t28/json2java/idea/validator/NameValidatorTest.java
// Path: idea/src/main/java/io/t28/json2java/idea/Json2JavaBundle.java // public class Json2JavaBundle extends AbstractBundle { // private static final String BUNDLE = "messages.Json2Java4IdeaBundle"; // // public Json2JavaBundle() { // super(BUNDLE); // } // // @Nonnull // public static Json2JavaBundle getInstance() { // return new Json2JavaBundle(); // } // // @Nonnull // @CheckReturnValue // public String message(@Nonnull @PropertyKey(resourceBundle = BUNDLE) String key, @Nonnull Object... objects) { // return getMessage(key, objects); // } // }
import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiNameHelper; import com.intellij.testFramework.fixtures.IdeaProjectTestFixture; import com.intellij.testFramework.fixtures.IdeaTestFixtureFactory; import com.intellij.testFramework.fixtures.TestFixtureBuilder; import com.intellij.util.ThrowableRunnable; import com.intellij.util.ui.UIUtil; import io.t28.json2java.idea.Json2JavaBundle; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat;
/* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.idea.validator; public class NameValidatorTest { private static final TestFixtureBuilder<IdeaProjectTestFixture> PRIJECT_BUILDER = IdeaTestFixtureFactory .getFixtureFactory() .createFixtureBuilder(NameValidator.class.getName()); private static IdeaProjectTestFixture fixture;
// Path: idea/src/main/java/io/t28/json2java/idea/Json2JavaBundle.java // public class Json2JavaBundle extends AbstractBundle { // private static final String BUNDLE = "messages.Json2Java4IdeaBundle"; // // public Json2JavaBundle() { // super(BUNDLE); // } // // @Nonnull // public static Json2JavaBundle getInstance() { // return new Json2JavaBundle(); // } // // @Nonnull // @CheckReturnValue // public String message(@Nonnull @PropertyKey(resourceBundle = BUNDLE) String key, @Nonnull Object... objects) { // return getMessage(key, objects); // } // } // Path: idea/src/test/java/io/t28/json2java/idea/validator/NameValidatorTest.java import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiNameHelper; import com.intellij.testFramework.fixtures.IdeaProjectTestFixture; import com.intellij.testFramework.fixtures.IdeaTestFixtureFactory; import com.intellij.testFramework.fixtures.TestFixtureBuilder; import com.intellij.util.ThrowableRunnable; import com.intellij.util.ui.UIUtil; import io.t28.json2java.idea.Json2JavaBundle; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; /* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.idea.validator; public class NameValidatorTest { private static final TestFixtureBuilder<IdeaProjectTestFixture> PRIJECT_BUILDER = IdeaTestFixtureFactory .getFixtureFactory() .createFixtureBuilder(NameValidator.class.getName()); private static IdeaProjectTestFixture fixture;
private Json2JavaBundle bundle;
t28hub/json2java4idea
core/src/test/java/io/t28/json2java/core/json/JsonNumberTest.java
// Path: core/src/test/java/io/t28/json2java/core/Assertions.java // @Nonnull // @CheckReturnValue // public static JsonValueAssert assertThat(@Nullable JsonValue actual) { // return new JsonValueAssert(actual); // }
import com.squareup.javapoet.TypeName; import org.junit.Before; import org.junit.Test; import static io.t28.json2java.core.Assertions.assertThat;
/* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.core.json; public class JsonNumberTest { private JsonNumber underTest; @Before public void setUp() throws Exception { underTest = new JsonNumber(int.class, 42); } @Test public void getType() throws Exception { // exercise final TypeName actual = underTest.getType(); // verify
// Path: core/src/test/java/io/t28/json2java/core/Assertions.java // @Nonnull // @CheckReturnValue // public static JsonValueAssert assertThat(@Nullable JsonValue actual) { // return new JsonValueAssert(actual); // } // Path: core/src/test/java/io/t28/json2java/core/json/JsonNumberTest.java import com.squareup.javapoet.TypeName; import org.junit.Before; import org.junit.Test; import static io.t28.json2java.core.Assertions.assertThat; /* * Copyright (c) 2017 Tatsuya Maki * * 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.t28.json2java.core.json; public class JsonNumberTest { private JsonNumber underTest; @Before public void setUp() throws Exception { underTest = new JsonNumber(int.class, 42); } @Test public void getType() throws Exception { // exercise final TypeName actual = underTest.getType(); // verify
assertThat(actual)
ndandoulakis/ndTorrent
src/com/ndtorrent/gui/TrackersModel.java
// Path: src/com/ndtorrent/client/status/TrackerInfo.java // public final class TrackerInfo { // // private final String url; // private final int seeders; // private final int leechers; // private final int interval; // private final long updated_at; // private final boolean is_updating; // private final boolean is_error; // private final boolean is_timeout; // private final boolean is_tracker_error; // // public TrackerInfo(Session session) { // url = session.getUrl(); // is_updating = session.isUpdating(); // updated_at = is_updating ? 0 : session.updatedAt(); // seeders = is_updating ? 0 : session.getSeeders(); // leechers = is_updating ? 0 : session.getLeechers(); // interval = is_updating ? 0 : session.getInterval(); // is_timeout = is_updating ? false : session.isConnectionTimeout(); // is_error = is_updating ? false : session.isConnectionError(); // is_tracker_error = is_updating ? false : session.isTrackerError(); // } // // public String getUrl() { // return url; // } // // public int getSeeders() { // return seeders; // } // // public int getLeechers() { // return leechers; // } // // public int getInterval() { // return interval; // } // // public long getUpdatedAt() { // return updated_at; // } // // public boolean isUpdating() { // return is_updating; // } // // public boolean isConnectionError() { // return is_error; // } // // public boolean isConnectionTimeout() { // return is_timeout; // } // // public boolean isTrackerError() { // return is_tracker_error; // } // // }
import java.util.List; import javax.swing.table.AbstractTableModel; import com.ndtorrent.client.status.TrackerInfo;
package com.ndtorrent.gui; public class TrackersModel extends AbstractTableModel { private static final long serialVersionUID = 1L; private String[] column_names = { "Name", "Status", "Update In", "Seeds", "Peers" };
// Path: src/com/ndtorrent/client/status/TrackerInfo.java // public final class TrackerInfo { // // private final String url; // private final int seeders; // private final int leechers; // private final int interval; // private final long updated_at; // private final boolean is_updating; // private final boolean is_error; // private final boolean is_timeout; // private final boolean is_tracker_error; // // public TrackerInfo(Session session) { // url = session.getUrl(); // is_updating = session.isUpdating(); // updated_at = is_updating ? 0 : session.updatedAt(); // seeders = is_updating ? 0 : session.getSeeders(); // leechers = is_updating ? 0 : session.getLeechers(); // interval = is_updating ? 0 : session.getInterval(); // is_timeout = is_updating ? false : session.isConnectionTimeout(); // is_error = is_updating ? false : session.isConnectionError(); // is_tracker_error = is_updating ? false : session.isTrackerError(); // } // // public String getUrl() { // return url; // } // // public int getSeeders() { // return seeders; // } // // public int getLeechers() { // return leechers; // } // // public int getInterval() { // return interval; // } // // public long getUpdatedAt() { // return updated_at; // } // // public boolean isUpdating() { // return is_updating; // } // // public boolean isConnectionError() { // return is_error; // } // // public boolean isConnectionTimeout() { // return is_timeout; // } // // public boolean isTrackerError() { // return is_tracker_error; // } // // } // Path: src/com/ndtorrent/gui/TrackersModel.java import java.util.List; import javax.swing.table.AbstractTableModel; import com.ndtorrent.client.status.TrackerInfo; package com.ndtorrent.gui; public class TrackersModel extends AbstractTableModel { private static final long serialVersionUID = 1L; private String[] column_names = { "Name", "Status", "Update In", "Seeds", "Peers" };
private List<TrackerInfo> trackers;
ndandoulakis/ndTorrent
src/com/ndtorrent/client/tracker/NullSession.java
// Path: src/com/ndtorrent/client/ClientInfo.java // public interface ClientInfo { // // public String getID(); // // // public void getIP(); // // public int getPort(); // // // public void getKey(); // // public String getStorageLocation(); // // // public int maxOutgoingConnections(); // // // public int maxIncomingConnections(); // // }
import java.net.InetSocketAddress; import java.util.Collection; import java.util.Collections; import com.ndtorrent.client.ClientInfo;
package com.ndtorrent.client.tracker; public final class NullSession extends Session { private String url;
// Path: src/com/ndtorrent/client/ClientInfo.java // public interface ClientInfo { // // public String getID(); // // // public void getIP(); // // public int getPort(); // // // public void getKey(); // // public String getStorageLocation(); // // // public int maxOutgoingConnections(); // // // public int maxIncomingConnections(); // // } // Path: src/com/ndtorrent/client/tracker/NullSession.java import java.net.InetSocketAddress; import java.util.Collection; import java.util.Collections; import com.ndtorrent.client.ClientInfo; package com.ndtorrent.client.tracker; public final class NullSession extends Session { private String url;
protected NullSession(String url, ClientInfo client_info, String info_hash) {
ndandoulakis/ndTorrent
src/com/ndtorrent/gui/SpeedGraph.java
// Path: src/com/ndtorrent/client/RollingTotal.java // public final class RollingTotal { // // private double[] buckets; // private double total; // // public RollingTotal(int nbuckets) { // if (nbuckets < 1) // throw new IllegalArgumentException( // "nbuckets must be greater than zero"); // // buckets = new double[nbuckets]; // } // // public void add(double amount) { // buckets[0] += amount; // total += amount; // } // // public void roll() { // // Roll after you have queried the total. // // total -= buckets[buckets.length - 1]; // // for (int i = buckets.length - 1; i >= 1; i--) { // buckets[i] = buckets[i - 1]; // } // // buckets[0] = 0; // } // // public double total() { // return total; // } // // public double average() { // return total / buckets.length; // } // // public double[] array() { // return buckets; // } // // }
import java.awt.Color; import java.awt.Dimension; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.geom.Rectangle2D; import javax.swing.JComponent; import com.ndtorrent.client.RollingTotal;
package com.ndtorrent.gui; public final class SpeedGraph extends JComponent { private static final long serialVersionUID = 1L; // TODO use a timer to repaint private Color bg_color = new Color(0xE3EADA); private Color color1 = new Color(0xFF8800); private Color color2 = new Color(0x1F8800); private Color color3 = new Color(0x8B8E87);
// Path: src/com/ndtorrent/client/RollingTotal.java // public final class RollingTotal { // // private double[] buckets; // private double total; // // public RollingTotal(int nbuckets) { // if (nbuckets < 1) // throw new IllegalArgumentException( // "nbuckets must be greater than zero"); // // buckets = new double[nbuckets]; // } // // public void add(double amount) { // buckets[0] += amount; // total += amount; // } // // public void roll() { // // Roll after you have queried the total. // // total -= buckets[buckets.length - 1]; // // for (int i = buckets.length - 1; i >= 1; i--) { // buckets[i] = buckets[i - 1]; // } // // buckets[0] = 0; // } // // public double total() { // return total; // } // // public double average() { // return total / buckets.length; // } // // public double[] array() { // return buckets; // } // // } // Path: src/com/ndtorrent/gui/SpeedGraph.java import java.awt.Color; import java.awt.Dimension; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.geom.Rectangle2D; import javax.swing.JComponent; import com.ndtorrent.client.RollingTotal; package com.ndtorrent.gui; public final class SpeedGraph extends JComponent { private static final long serialVersionUID = 1L; // TODO use a timer to repaint private Color bg_color = new Color(0xE3EADA); private Color color1 = new Color(0xFF8800); private Color color2 = new Color(0x1F8800); private Color color3 = new Color(0x8B8E87);
private RollingTotal input_rate = new RollingTotal(5 * 60);
ndandoulakis/ndTorrent
src/com/ndtorrent/client/status/TrackerInfo.java
// Path: src/com/ndtorrent/client/tracker/Session.java // public abstract class Session { // // Session and its subclasses are not thread safe. // // Do not call any query method while Session.isUpdating() returns true. // // protected ClientInfo client_info; // protected String info_hash; // // protected Session(ClientInfo client_info, String info_hash) { // this.client_info = client_info; // this.info_hash = info_hash; // } // // public static final Session create(String url, ClientInfo client_info, // String info_hash) { // if (url != null) // if (url.startsWith("udp")) // return new UdpSession(url, client_info, info_hash); // else if (url.startsWith("http")) // return new HttpSession(url, client_info, info_hash); // // return new NullSession(url, client_info, info_hash); // } // // public abstract String getUrl(); // // public abstract void update(Event event, long uploaded, long downloaded, // long left); // // public abstract Event lastEvent(); // // public abstract long updatedAt(); // // public final boolean isUpdateError() { // if (isUpdating()) // return false; // if (isConnectionTimeout()) // return true; // if (isConnectionError()) // return true; // if (isTrackerError()) // return true; // return false; // } // // public abstract boolean isConnectionError(); // // public abstract boolean isConnectionTimeout(); // // public abstract boolean isUpdating(); // // public abstract boolean isValidResponse(); // // public abstract boolean isTrackerError(); // // public abstract int getInterval(); // // public abstract int getLeechers(); // // public abstract int getSeeders(); // // public abstract Collection<InetSocketAddress> getPeers(); // // final InetSocketAddress peerAddress(ByteBuffer bb, int ofs, int ip_length) { // if (ofs < 0 || ofs >= bb.capacity()) // return null; // // byte[] ip = ByteBuffer.allocate(ip_length).putInt(bb.getInt(ofs)).array(); // int port = bb.getShort(ofs + ip_length) & 0xFFFF; // // try { // return new InetSocketAddress(InetAddress.getByAddress(ip), port); // } catch (UnknownHostException e) { // e.printStackTrace(); // return null; // } // } // // }
import com.ndtorrent.client.tracker.Session;
package com.ndtorrent.client.status; public final class TrackerInfo { private final String url; private final int seeders; private final int leechers; private final int interval; private final long updated_at; private final boolean is_updating; private final boolean is_error; private final boolean is_timeout; private final boolean is_tracker_error;
// Path: src/com/ndtorrent/client/tracker/Session.java // public abstract class Session { // // Session and its subclasses are not thread safe. // // Do not call any query method while Session.isUpdating() returns true. // // protected ClientInfo client_info; // protected String info_hash; // // protected Session(ClientInfo client_info, String info_hash) { // this.client_info = client_info; // this.info_hash = info_hash; // } // // public static final Session create(String url, ClientInfo client_info, // String info_hash) { // if (url != null) // if (url.startsWith("udp")) // return new UdpSession(url, client_info, info_hash); // else if (url.startsWith("http")) // return new HttpSession(url, client_info, info_hash); // // return new NullSession(url, client_info, info_hash); // } // // public abstract String getUrl(); // // public abstract void update(Event event, long uploaded, long downloaded, // long left); // // public abstract Event lastEvent(); // // public abstract long updatedAt(); // // public final boolean isUpdateError() { // if (isUpdating()) // return false; // if (isConnectionTimeout()) // return true; // if (isConnectionError()) // return true; // if (isTrackerError()) // return true; // return false; // } // // public abstract boolean isConnectionError(); // // public abstract boolean isConnectionTimeout(); // // public abstract boolean isUpdating(); // // public abstract boolean isValidResponse(); // // public abstract boolean isTrackerError(); // // public abstract int getInterval(); // // public abstract int getLeechers(); // // public abstract int getSeeders(); // // public abstract Collection<InetSocketAddress> getPeers(); // // final InetSocketAddress peerAddress(ByteBuffer bb, int ofs, int ip_length) { // if (ofs < 0 || ofs >= bb.capacity()) // return null; // // byte[] ip = ByteBuffer.allocate(ip_length).putInt(bb.getInt(ofs)).array(); // int port = bb.getShort(ofs + ip_length) & 0xFFFF; // // try { // return new InetSocketAddress(InetAddress.getByAddress(ip), port); // } catch (UnknownHostException e) { // e.printStackTrace(); // return null; // } // } // // } // Path: src/com/ndtorrent/client/status/TrackerInfo.java import com.ndtorrent.client.tracker.Session; package com.ndtorrent.client.status; public final class TrackerInfo { private final String url; private final int seeders; private final int leechers; private final int interval; private final long updated_at; private final boolean is_updating; private final boolean is_error; private final boolean is_timeout; private final boolean is_tracker_error;
public TrackerInfo(Session session) {
ndandoulakis/ndTorrent
src/com/ndtorrent/client/Client.java
// Path: src/com/ndtorrent/client/status/StatusObserver.java // public interface StatusObserver { // // // A Swing component could implement asyncMethods like this // // { SwingUtilities.invokeLater(new Runnable() {set/draw status}); } // // void asyncConnections(final List<ConnectionInfo> connections, // String info_hash); // // void asyncPieces(final List<PieceInfo> pieces, String info_hash); // // void asyncTrackers(final List<TrackerInfo> trackers, String info_hash); // // void asyncTorrentStatus(final TorrentInfo torrent, String info_hash); // // }
import java.util.HashMap; import java.util.Map; import com.ndtorrent.client.status.StatusObserver;
e.printStackTrace(); } for (Peer peer : peers.values()) { peer.close(); } for (Peer peer : peers.values()) { try { peer.join(); } catch (InterruptedException e) { e.printStackTrace(); } } peers.clear(); } @Override public String getID() { return id; } @Override public int getPort() { return server == null ? 0 : server.getPort(); } @Override public String getStorageLocation() { return storage_location; }
// Path: src/com/ndtorrent/client/status/StatusObserver.java // public interface StatusObserver { // // // A Swing component could implement asyncMethods like this // // { SwingUtilities.invokeLater(new Runnable() {set/draw status}); } // // void asyncConnections(final List<ConnectionInfo> connections, // String info_hash); // // void asyncPieces(final List<PieceInfo> pieces, String info_hash); // // void asyncTrackers(final List<TrackerInfo> trackers, String info_hash); // // void asyncTorrentStatus(final TorrentInfo torrent, String info_hash); // // } // Path: src/com/ndtorrent/client/Client.java import java.util.HashMap; import java.util.Map; import com.ndtorrent.client.status.StatusObserver; e.printStackTrace(); } for (Peer peer : peers.values()) { peer.close(); } for (Peer peer : peers.values()) { try { peer.join(); } catch (InterruptedException e) { e.printStackTrace(); } } peers.clear(); } @Override public String getID() { return id; } @Override public int getPort() { return server == null ? 0 : server.getPort(); } @Override public String getStorageLocation() { return storage_location; }
public void addStatusObserver(StatusObserver observer, String info_hash) {
ndandoulakis/ndTorrent
src/com/ndtorrent/gui/BarRenderer.java
// Path: src/com/ndtorrent/client/status/PieceInfo.java // public final class PieceInfo { // // private final int index; // private final int length; // private final int num_blocks; // private final BitSet available; // private final BitSet requested; // // public PieceInfo(Piece piece) { // index = piece.getIndex(); // length = piece.getLength(); // num_blocks = piece.numBlocks(); // available = piece.getAvailableBlocks(); // requested = (BitSet) piece.getNotRequested().clone(); // requested.flip(0, num_blocks); // requested.andNot(available); // } // // public int getIndex() { // return index; // } // // public int getLength() { // return length; // } // // public int numBlocks() { // return num_blocks; // } // // public int numAvailableBlocks() { // return available.cardinality(); // } // // public BitSet getAvailableBlocks() { // return available; // } // // public BitSet getRequestedBlocks() { // return requested; // } // // } // // Path: src/com/ndtorrent/client/status/TorrentInfo.java // public final class TorrentInfo { // // private final BitSet available; // private final BitSet missing; // private final int num_pieces; // private final String name; // private final long remaining_length; // private final long total_length; // private final long completion_time; // private final double input_rate; // private final double output_rate; // // public TorrentInfo(Torrent torrent, BitSet missing, long completion_time, // double input_rate, double output_rate) { // // available = torrent.getAvailablePieces(); // this.missing = missing; // num_pieces = torrent.numPieces(); // name = torrent.getName(); // remaining_length = torrent.getRemainingLength(); // total_length = torrent.getTotalLength(); // this.completion_time = completion_time; // this.input_rate = input_rate; // this.output_rate = output_rate; // // } // // public BitSet getAvailablePieces() { // return available; // } // // public BitSet getMissingPieces() { // return missing; // } // // public int numPieces() { // return num_pieces; // } // // public String getName() { // return name; // } // // public long getRemainingLength() { // return remaining_length; // } // // public long getTotalLength() { // return total_length; // } // // public long getCompletionTime() { // return completion_time; // } // // public double getInputRate() { // return input_rate; // } // // public double getOutputRate() { // return output_rate; // } // // }
import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.util.BitSet; import javax.swing.JComponent; import javax.swing.JTable; import javax.swing.table.TableCellRenderer; import com.ndtorrent.client.status.PieceInfo; import com.ndtorrent.client.status.TorrentInfo;
if (width < half_image.getWidth()) { Graphics2D g2; g2 = half_image.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2.drawImage(full_image, 0, 0, half_image.getWidth(), 1, null); g2.dispose(); g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); g2.drawImage(half_image, 0, 0, width, height, null); } else if (width < full_image.getWidth()) { Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2.drawImage(full_image, 0, 0, width, height, null); } else { g.drawImage(full_image, 0, 0, width, height, null); } } @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
// Path: src/com/ndtorrent/client/status/PieceInfo.java // public final class PieceInfo { // // private final int index; // private final int length; // private final int num_blocks; // private final BitSet available; // private final BitSet requested; // // public PieceInfo(Piece piece) { // index = piece.getIndex(); // length = piece.getLength(); // num_blocks = piece.numBlocks(); // available = piece.getAvailableBlocks(); // requested = (BitSet) piece.getNotRequested().clone(); // requested.flip(0, num_blocks); // requested.andNot(available); // } // // public int getIndex() { // return index; // } // // public int getLength() { // return length; // } // // public int numBlocks() { // return num_blocks; // } // // public int numAvailableBlocks() { // return available.cardinality(); // } // // public BitSet getAvailableBlocks() { // return available; // } // // public BitSet getRequestedBlocks() { // return requested; // } // // } // // Path: src/com/ndtorrent/client/status/TorrentInfo.java // public final class TorrentInfo { // // private final BitSet available; // private final BitSet missing; // private final int num_pieces; // private final String name; // private final long remaining_length; // private final long total_length; // private final long completion_time; // private final double input_rate; // private final double output_rate; // // public TorrentInfo(Torrent torrent, BitSet missing, long completion_time, // double input_rate, double output_rate) { // // available = torrent.getAvailablePieces(); // this.missing = missing; // num_pieces = torrent.numPieces(); // name = torrent.getName(); // remaining_length = torrent.getRemainingLength(); // total_length = torrent.getTotalLength(); // this.completion_time = completion_time; // this.input_rate = input_rate; // this.output_rate = output_rate; // // } // // public BitSet getAvailablePieces() { // return available; // } // // public BitSet getMissingPieces() { // return missing; // } // // public int numPieces() { // return num_pieces; // } // // public String getName() { // return name; // } // // public long getRemainingLength() { // return remaining_length; // } // // public long getTotalLength() { // return total_length; // } // // public long getCompletionTime() { // return completion_time; // } // // public double getInputRate() { // return input_rate; // } // // public double getOutputRate() { // return output_rate; // } // // } // Path: src/com/ndtorrent/gui/BarRenderer.java import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.util.BitSet; import javax.swing.JComponent; import javax.swing.JTable; import javax.swing.table.TableCellRenderer; import com.ndtorrent.client.status.PieceInfo; import com.ndtorrent.client.status.TorrentInfo; if (width < half_image.getWidth()) { Graphics2D g2; g2 = half_image.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2.drawImage(full_image, 0, 0, half_image.getWidth(), 1, null); g2.dispose(); g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); g2.drawImage(half_image, 0, 0, width, height, null); } else if (width < full_image.getWidth()) { Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2.drawImage(full_image, 0, 0, width, height, null); } else { g.drawImage(full_image, 0, 0, width, height, null); } } @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
if (value instanceof TorrentInfo) {
ndandoulakis/ndTorrent
src/com/ndtorrent/gui/BarRenderer.java
// Path: src/com/ndtorrent/client/status/PieceInfo.java // public final class PieceInfo { // // private final int index; // private final int length; // private final int num_blocks; // private final BitSet available; // private final BitSet requested; // // public PieceInfo(Piece piece) { // index = piece.getIndex(); // length = piece.getLength(); // num_blocks = piece.numBlocks(); // available = piece.getAvailableBlocks(); // requested = (BitSet) piece.getNotRequested().clone(); // requested.flip(0, num_blocks); // requested.andNot(available); // } // // public int getIndex() { // return index; // } // // public int getLength() { // return length; // } // // public int numBlocks() { // return num_blocks; // } // // public int numAvailableBlocks() { // return available.cardinality(); // } // // public BitSet getAvailableBlocks() { // return available; // } // // public BitSet getRequestedBlocks() { // return requested; // } // // } // // Path: src/com/ndtorrent/client/status/TorrentInfo.java // public final class TorrentInfo { // // private final BitSet available; // private final BitSet missing; // private final int num_pieces; // private final String name; // private final long remaining_length; // private final long total_length; // private final long completion_time; // private final double input_rate; // private final double output_rate; // // public TorrentInfo(Torrent torrent, BitSet missing, long completion_time, // double input_rate, double output_rate) { // // available = torrent.getAvailablePieces(); // this.missing = missing; // num_pieces = torrent.numPieces(); // name = torrent.getName(); // remaining_length = torrent.getRemainingLength(); // total_length = torrent.getTotalLength(); // this.completion_time = completion_time; // this.input_rate = input_rate; // this.output_rate = output_rate; // // } // // public BitSet getAvailablePieces() { // return available; // } // // public BitSet getMissingPieces() { // return missing; // } // // public int numPieces() { // return num_pieces; // } // // public String getName() { // return name; // } // // public long getRemainingLength() { // return remaining_length; // } // // public long getTotalLength() { // return total_length; // } // // public long getCompletionTime() { // return completion_time; // } // // public double getInputRate() { // return input_rate; // } // // public double getOutputRate() { // return output_rate; // } // // }
import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.util.BitSet; import javax.swing.JComponent; import javax.swing.JTable; import javax.swing.table.TableCellRenderer; import com.ndtorrent.client.status.PieceInfo; import com.ndtorrent.client.status.TorrentInfo;
RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2.drawImage(full_image, 0, 0, half_image.getWidth(), 1, null); g2.dispose(); g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); g2.drawImage(half_image, 0, 0, width, height, null); } else if (width < full_image.getWidth()) { Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2.drawImage(full_image, 0, 0, width, height, null); } else { g.drawImage(full_image, 0, 0, width, height, null); } } @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { if (value instanceof TorrentInfo) { TorrentInfo info = (TorrentInfo) value; setBits(info.getAvailablePieces(), info.getMissingPieces(), info.numPieces());
// Path: src/com/ndtorrent/client/status/PieceInfo.java // public final class PieceInfo { // // private final int index; // private final int length; // private final int num_blocks; // private final BitSet available; // private final BitSet requested; // // public PieceInfo(Piece piece) { // index = piece.getIndex(); // length = piece.getLength(); // num_blocks = piece.numBlocks(); // available = piece.getAvailableBlocks(); // requested = (BitSet) piece.getNotRequested().clone(); // requested.flip(0, num_blocks); // requested.andNot(available); // } // // public int getIndex() { // return index; // } // // public int getLength() { // return length; // } // // public int numBlocks() { // return num_blocks; // } // // public int numAvailableBlocks() { // return available.cardinality(); // } // // public BitSet getAvailableBlocks() { // return available; // } // // public BitSet getRequestedBlocks() { // return requested; // } // // } // // Path: src/com/ndtorrent/client/status/TorrentInfo.java // public final class TorrentInfo { // // private final BitSet available; // private final BitSet missing; // private final int num_pieces; // private final String name; // private final long remaining_length; // private final long total_length; // private final long completion_time; // private final double input_rate; // private final double output_rate; // // public TorrentInfo(Torrent torrent, BitSet missing, long completion_time, // double input_rate, double output_rate) { // // available = torrent.getAvailablePieces(); // this.missing = missing; // num_pieces = torrent.numPieces(); // name = torrent.getName(); // remaining_length = torrent.getRemainingLength(); // total_length = torrent.getTotalLength(); // this.completion_time = completion_time; // this.input_rate = input_rate; // this.output_rate = output_rate; // // } // // public BitSet getAvailablePieces() { // return available; // } // // public BitSet getMissingPieces() { // return missing; // } // // public int numPieces() { // return num_pieces; // } // // public String getName() { // return name; // } // // public long getRemainingLength() { // return remaining_length; // } // // public long getTotalLength() { // return total_length; // } // // public long getCompletionTime() { // return completion_time; // } // // public double getInputRate() { // return input_rate; // } // // public double getOutputRate() { // return output_rate; // } // // } // Path: src/com/ndtorrent/gui/BarRenderer.java import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.util.BitSet; import javax.swing.JComponent; import javax.swing.JTable; import javax.swing.table.TableCellRenderer; import com.ndtorrent.client.status.PieceInfo; import com.ndtorrent.client.status.TorrentInfo; RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2.drawImage(full_image, 0, 0, half_image.getWidth(), 1, null); g2.dispose(); g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); g2.drawImage(half_image, 0, 0, width, height, null); } else if (width < full_image.getWidth()) { Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2.drawImage(full_image, 0, 0, width, height, null); } else { g.drawImage(full_image, 0, 0, width, height, null); } } @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { if (value instanceof TorrentInfo) { TorrentInfo info = (TorrentInfo) value; setBits(info.getAvailablePieces(), info.getMissingPieces(), info.numPieces());
} else if (value instanceof PieceInfo) {
ndandoulakis/ndTorrent
src/com/ndtorrent/client/status/PieceInfo.java
// Path: src/com/ndtorrent/client/Piece.java // public final class Piece { // private ByteBuffer data; // // private int index; // private int piece_length; // private int num_blocks; // private int block_length; // private int tail_length; // // private BitSet available; // private BitSet not_requested; // private BitSet reserved; // // public Piece(int index, int length) { // this(index, length, 1 * 1024); // } // // public Piece(int index, int piece_length, int block_length) { // data = ByteBuffer.allocate(piece_length); // // this.index = index; // this.piece_length = piece_length; // this.block_length = block_length; // // num_blocks = (piece_length + block_length - 1) / block_length; // available = new BitSet(num_blocks); // not_requested = new BitSet(num_blocks); // not_requested.set(0, num_blocks, true); // reserved = new BitSet(num_blocks); // // tail_length = piece_length % block_length; // if (piece_length != 0 && tail_length == 0) // tail_length = block_length; // } // // public boolean isComplete() { // return getRemainingLength() == 0; // } // // public void restorePendingRequests(BitSet requests) { // not_requested.set(0, num_blocks, true); // not_requested.andNot(requests); // not_requested.andNot(available); // // reserved.and(requests); // } // // public void setBlocksAsReserved(int fromIndex, int toIndex) { // reserved.set(fromIndex, toIndex, true); // } // // public BitSet getReservedBlocks() { // return reserved; // } // // public void setBlocksAsRequested(int fromIndex, int toIndex) { // not_requested.set(fromIndex, toIndex, false); // } // // public BitSet getNotRequested() { // return not_requested; // } // // public ByteBuffer getData() { // return data; // } // // public int numBlocks() { // return num_blocks; // } // // public BitSet getAvailableBlocks() { // return (BitSet) available.clone(); // } // // public int numAvailableBlocks() { // return available.cardinality(); // } // // public int getIndex() { // return index; // } // // public int getLength() { // return piece_length; // } // // public int getRemainingLength() { // int completed = available.cardinality() * block_length; // if (available.get(num_blocks - 1)) // completed += tail_length - block_length; // return piece_length - completed; // } // // public int getBlockIndex(int offset) { // return offset % block_length == 0 ? offset / block_length : -1; // } // // public int getBlockOffset(int index) { // return index * block_length; // } // // public int getBlockLength(int index) { // return index + 1 == num_blocks ? tail_length : block_length; // } // // private boolean validBlockRegion(int offset, int length) { // if (offset < 0 || offset % block_length != 0) // return false; // return offset + length <= data.capacity(); // } // // public void write(Message block) { // int length = block.getPayloadLength() - 2 * 4; // int offset = block.getBlockBegin(); // if (!validBlockRegion(offset, length)) // return; // // int start = getBlockIndex(offset); // int block_length = getBlockLength(start); // int nblocks = block.getBlockLength() / block_length; // if (nblocks * block_length < block.getBlockLength()) // nblocks++; // available.set(start, start + nblocks, true); // not_requested.set(start, start + nblocks, false); // // data.position(offset); // data.put(block.getData().array(), 1 + 2 * 4, length); // } // // }
import java.util.BitSet; import com.ndtorrent.client.Piece;
package com.ndtorrent.client.status; public final class PieceInfo { private final int index; private final int length; private final int num_blocks; private final BitSet available; private final BitSet requested;
// Path: src/com/ndtorrent/client/Piece.java // public final class Piece { // private ByteBuffer data; // // private int index; // private int piece_length; // private int num_blocks; // private int block_length; // private int tail_length; // // private BitSet available; // private BitSet not_requested; // private BitSet reserved; // // public Piece(int index, int length) { // this(index, length, 1 * 1024); // } // // public Piece(int index, int piece_length, int block_length) { // data = ByteBuffer.allocate(piece_length); // // this.index = index; // this.piece_length = piece_length; // this.block_length = block_length; // // num_blocks = (piece_length + block_length - 1) / block_length; // available = new BitSet(num_blocks); // not_requested = new BitSet(num_blocks); // not_requested.set(0, num_blocks, true); // reserved = new BitSet(num_blocks); // // tail_length = piece_length % block_length; // if (piece_length != 0 && tail_length == 0) // tail_length = block_length; // } // // public boolean isComplete() { // return getRemainingLength() == 0; // } // // public void restorePendingRequests(BitSet requests) { // not_requested.set(0, num_blocks, true); // not_requested.andNot(requests); // not_requested.andNot(available); // // reserved.and(requests); // } // // public void setBlocksAsReserved(int fromIndex, int toIndex) { // reserved.set(fromIndex, toIndex, true); // } // // public BitSet getReservedBlocks() { // return reserved; // } // // public void setBlocksAsRequested(int fromIndex, int toIndex) { // not_requested.set(fromIndex, toIndex, false); // } // // public BitSet getNotRequested() { // return not_requested; // } // // public ByteBuffer getData() { // return data; // } // // public int numBlocks() { // return num_blocks; // } // // public BitSet getAvailableBlocks() { // return (BitSet) available.clone(); // } // // public int numAvailableBlocks() { // return available.cardinality(); // } // // public int getIndex() { // return index; // } // // public int getLength() { // return piece_length; // } // // public int getRemainingLength() { // int completed = available.cardinality() * block_length; // if (available.get(num_blocks - 1)) // completed += tail_length - block_length; // return piece_length - completed; // } // // public int getBlockIndex(int offset) { // return offset % block_length == 0 ? offset / block_length : -1; // } // // public int getBlockOffset(int index) { // return index * block_length; // } // // public int getBlockLength(int index) { // return index + 1 == num_blocks ? tail_length : block_length; // } // // private boolean validBlockRegion(int offset, int length) { // if (offset < 0 || offset % block_length != 0) // return false; // return offset + length <= data.capacity(); // } // // public void write(Message block) { // int length = block.getPayloadLength() - 2 * 4; // int offset = block.getBlockBegin(); // if (!validBlockRegion(offset, length)) // return; // // int start = getBlockIndex(offset); // int block_length = getBlockLength(start); // int nblocks = block.getBlockLength() / block_length; // if (nblocks * block_length < block.getBlockLength()) // nblocks++; // available.set(start, start + nblocks, true); // not_requested.set(start, start + nblocks, false); // // data.position(offset); // data.put(block.getData().array(), 1 + 2 * 4, length); // } // // } // Path: src/com/ndtorrent/client/status/PieceInfo.java import java.util.BitSet; import com.ndtorrent.client.Piece; package com.ndtorrent.client.status; public final class PieceInfo { private final int index; private final int length; private final int num_blocks; private final BitSet available; private final BitSet requested;
public PieceInfo(Piece piece) {
ndandoulakis/ndTorrent
src/com/ndtorrent/gui/PiecesModel.java
// Path: src/com/ndtorrent/client/status/PieceInfo.java // public final class PieceInfo { // // private final int index; // private final int length; // private final int num_blocks; // private final BitSet available; // private final BitSet requested; // // public PieceInfo(Piece piece) { // index = piece.getIndex(); // length = piece.getLength(); // num_blocks = piece.numBlocks(); // available = piece.getAvailableBlocks(); // requested = (BitSet) piece.getNotRequested().clone(); // requested.flip(0, num_blocks); // requested.andNot(available); // } // // public int getIndex() { // return index; // } // // public int getLength() { // return length; // } // // public int numBlocks() { // return num_blocks; // } // // public int numAvailableBlocks() { // return available.cardinality(); // } // // public BitSet getAvailableBlocks() { // return available; // } // // public BitSet getRequestedBlocks() { // return requested; // } // // }
import java.util.List; import javax.swing.table.AbstractTableModel; import com.ndtorrent.client.status.PieceInfo;
package com.ndtorrent.gui; public final class PiecesModel extends AbstractTableModel { private static final long serialVersionUID = 1L; private String[] column_names = { "#", "Size", "Blocks", "Completed", "" };
// Path: src/com/ndtorrent/client/status/PieceInfo.java // public final class PieceInfo { // // private final int index; // private final int length; // private final int num_blocks; // private final BitSet available; // private final BitSet requested; // // public PieceInfo(Piece piece) { // index = piece.getIndex(); // length = piece.getLength(); // num_blocks = piece.numBlocks(); // available = piece.getAvailableBlocks(); // requested = (BitSet) piece.getNotRequested().clone(); // requested.flip(0, num_blocks); // requested.andNot(available); // } // // public int getIndex() { // return index; // } // // public int getLength() { // return length; // } // // public int numBlocks() { // return num_blocks; // } // // public int numAvailableBlocks() { // return available.cardinality(); // } // // public BitSet getAvailableBlocks() { // return available; // } // // public BitSet getRequestedBlocks() { // return requested; // } // // } // Path: src/com/ndtorrent/gui/PiecesModel.java import java.util.List; import javax.swing.table.AbstractTableModel; import com.ndtorrent.client.status.PieceInfo; package com.ndtorrent.gui; public final class PiecesModel extends AbstractTableModel { private static final long serialVersionUID = 1L; private String[] column_names = { "#", "Size", "Blocks", "Completed", "" };
private List<PieceInfo> pieces;
ndandoulakis/ndTorrent
src/com/ndtorrent/gui/TorrentsModel.java
// Path: src/com/ndtorrent/client/status/TorrentInfo.java // public final class TorrentInfo { // // private final BitSet available; // private final BitSet missing; // private final int num_pieces; // private final String name; // private final long remaining_length; // private final long total_length; // private final long completion_time; // private final double input_rate; // private final double output_rate; // // public TorrentInfo(Torrent torrent, BitSet missing, long completion_time, // double input_rate, double output_rate) { // // available = torrent.getAvailablePieces(); // this.missing = missing; // num_pieces = torrent.numPieces(); // name = torrent.getName(); // remaining_length = torrent.getRemainingLength(); // total_length = torrent.getTotalLength(); // this.completion_time = completion_time; // this.input_rate = input_rate; // this.output_rate = output_rate; // // } // // public BitSet getAvailablePieces() { // return available; // } // // public BitSet getMissingPieces() { // return missing; // } // // public int numPieces() { // return num_pieces; // } // // public String getName() { // return name; // } // // public long getRemainingLength() { // return remaining_length; // } // // public long getTotalLength() { // return total_length; // } // // public long getCompletionTime() { // return completion_time; // } // // public double getInputRate() { // return input_rate; // } // // public double getOutputRate() { // return output_rate; // } // // }
import javax.swing.table.AbstractTableModel; import com.ndtorrent.client.status.TorrentInfo;
package com.ndtorrent.gui; public class TorrentsModel extends AbstractTableModel { private static final long serialVersionUID = 1L; private String[] column_names = { "Name", "Size", "Remaining", "Status", "Progress", "ETA", "Dn Speed", "Up Speed" };
// Path: src/com/ndtorrent/client/status/TorrentInfo.java // public final class TorrentInfo { // // private final BitSet available; // private final BitSet missing; // private final int num_pieces; // private final String name; // private final long remaining_length; // private final long total_length; // private final long completion_time; // private final double input_rate; // private final double output_rate; // // public TorrentInfo(Torrent torrent, BitSet missing, long completion_time, // double input_rate, double output_rate) { // // available = torrent.getAvailablePieces(); // this.missing = missing; // num_pieces = torrent.numPieces(); // name = torrent.getName(); // remaining_length = torrent.getRemainingLength(); // total_length = torrent.getTotalLength(); // this.completion_time = completion_time; // this.input_rate = input_rate; // this.output_rate = output_rate; // // } // // public BitSet getAvailablePieces() { // return available; // } // // public BitSet getMissingPieces() { // return missing; // } // // public int numPieces() { // return num_pieces; // } // // public String getName() { // return name; // } // // public long getRemainingLength() { // return remaining_length; // } // // public long getTotalLength() { // return total_length; // } // // public long getCompletionTime() { // return completion_time; // } // // public double getInputRate() { // return input_rate; // } // // public double getOutputRate() { // return output_rate; // } // // } // Path: src/com/ndtorrent/gui/TorrentsModel.java import javax.swing.table.AbstractTableModel; import com.ndtorrent.client.status.TorrentInfo; package com.ndtorrent.gui; public class TorrentsModel extends AbstractTableModel { private static final long serialVersionUID = 1L; private String[] column_names = { "Name", "Size", "Remaining", "Status", "Progress", "ETA", "Dn Speed", "Up Speed" };
private TorrentInfo torrent;
ndandoulakis/ndTorrent
src/com/ndtorrent/gui/ConnectionsModel.java
// Path: src/com/ndtorrent/client/status/ConnectionInfo.java // public final class ConnectionInfo { // // // TODO add the sizes of various message queues // private final String address; // private final String id; // private final double input_rate; // private final double output_rate; // private final long input_total; // private final long output_total; // private final int incoming_requests; // private final int outgoing_requests; // private final boolean am_choked; // private final boolean am_interested; // private final boolean is_choked; // private final boolean is_interested; // private final boolean is_optimistic; // private final boolean is_former_optimistic; // private final boolean am_snubbed; // private final boolean am_initiator; // // public ConnectionInfo(PeerChannel channel) { // address = channel.socket.getRemoteIP(); // id = channel.socket.getInputHandshake().getID(); // input_rate = channel.socket.inputPerSec(); // output_rate = channel.socket.outputPerSec(); // input_total = channel.socket.getInputTotal(); // output_total = channel.socket.getOutputTotal(); // incoming_requests = channel.numIncomingRequests(); // outgoing_requests = channel.numOutgoingRequests(); // am_choked = channel.amChoked(); // am_interested = channel.amInterested(); // is_choked = channel.isChoked(); // is_interested = channel.isInterested(); // is_optimistic = channel.isOptimistic(); // is_former_optimistic = channel.isFormerOptimistic(); // am_snubbed = channel.amSnubbed(); // am_initiator = channel.amInitiator(); // } // // public String getIP() { // return address; // } // // public String getID() { // return id; // } // // public double getInputRate() { // return input_rate; // } // // public double getOutputRate() { // return output_rate; // } // // public long getInputTotal() { // return input_total; // } // // public long getOutputTotal() { // return output_total; // } // // public int numIncomingRequests() { // return incoming_requests; // } // // public int numOutgoingRequests() { // return outgoing_requests; // } // // public boolean amChoked() { // return am_choked; // } // // public boolean amInterested() { // return am_interested; // } // // public boolean isChoked() { // return is_choked; // } // // public boolean isInterested() { // return is_interested; // } // // public boolean isOptimistic() { // return is_optimistic; // } // // public boolean isFormerOptimistic() { // return is_former_optimistic; // } // // public boolean amSnubbed() { // return am_snubbed; // } // // public boolean isInitiator() { // return am_initiator; // } // // }
import java.util.List; import javax.swing.table.AbstractTableModel; import com.ndtorrent.client.status.ConnectionInfo;
package com.ndtorrent.gui; public final class ConnectionsModel extends AbstractTableModel { private static final long serialVersionUID = 1L; private String[] column_names = { "IP", "Client", "Flags", "Dn Speed", "Up Speed", "Reqs", "Received", "Sent" };
// Path: src/com/ndtorrent/client/status/ConnectionInfo.java // public final class ConnectionInfo { // // // TODO add the sizes of various message queues // private final String address; // private final String id; // private final double input_rate; // private final double output_rate; // private final long input_total; // private final long output_total; // private final int incoming_requests; // private final int outgoing_requests; // private final boolean am_choked; // private final boolean am_interested; // private final boolean is_choked; // private final boolean is_interested; // private final boolean is_optimistic; // private final boolean is_former_optimistic; // private final boolean am_snubbed; // private final boolean am_initiator; // // public ConnectionInfo(PeerChannel channel) { // address = channel.socket.getRemoteIP(); // id = channel.socket.getInputHandshake().getID(); // input_rate = channel.socket.inputPerSec(); // output_rate = channel.socket.outputPerSec(); // input_total = channel.socket.getInputTotal(); // output_total = channel.socket.getOutputTotal(); // incoming_requests = channel.numIncomingRequests(); // outgoing_requests = channel.numOutgoingRequests(); // am_choked = channel.amChoked(); // am_interested = channel.amInterested(); // is_choked = channel.isChoked(); // is_interested = channel.isInterested(); // is_optimistic = channel.isOptimistic(); // is_former_optimistic = channel.isFormerOptimistic(); // am_snubbed = channel.amSnubbed(); // am_initiator = channel.amInitiator(); // } // // public String getIP() { // return address; // } // // public String getID() { // return id; // } // // public double getInputRate() { // return input_rate; // } // // public double getOutputRate() { // return output_rate; // } // // public long getInputTotal() { // return input_total; // } // // public long getOutputTotal() { // return output_total; // } // // public int numIncomingRequests() { // return incoming_requests; // } // // public int numOutgoingRequests() { // return outgoing_requests; // } // // public boolean amChoked() { // return am_choked; // } // // public boolean amInterested() { // return am_interested; // } // // public boolean isChoked() { // return is_choked; // } // // public boolean isInterested() { // return is_interested; // } // // public boolean isOptimistic() { // return is_optimistic; // } // // public boolean isFormerOptimistic() { // return is_former_optimistic; // } // // public boolean amSnubbed() { // return am_snubbed; // } // // public boolean isInitiator() { // return am_initiator; // } // // } // Path: src/com/ndtorrent/gui/ConnectionsModel.java import java.util.List; import javax.swing.table.AbstractTableModel; import com.ndtorrent.client.status.ConnectionInfo; package com.ndtorrent.gui; public final class ConnectionsModel extends AbstractTableModel { private static final long serialVersionUID = 1L; private String[] column_names = { "IP", "Client", "Flags", "Dn Speed", "Up Speed", "Reqs", "Received", "Sent" };
private List<ConnectionInfo> connections;
ndandoulakis/ndTorrent
src/com/ndtorrent/client/tracker/UdpSession.java
// Path: src/com/ndtorrent/client/ClientInfo.java // public interface ClientInfo { // // public String getID(); // // // public void getIP(); // // public int getPort(); // // // public void getKey(); // // public String getStorageLocation(); // // // public int maxOutgoingConnections(); // // // public int maxIncomingConnections(); // // }
import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.SocketTimeoutException; import java.net.URI; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collection; import java.util.Random; import com.ndtorrent.client.ClientInfo;
package com.ndtorrent.client.tracker; public final class UdpSession extends Session implements Runnable { // Implements the UDP tracker protocol static final long CONNECTION_ID = 0x41727101980L; static final int ACTION_CONNECT = 0; static final int ACTION_ANNOUNCE = 1; static final int ACTION_SCRAPE = 2; static final int ACTION_ERROR = 3; static final int ACTION_ERROR_LE = 0x03000000; static final int REQUEST_BODY_LENGTH = 2 * 20 + 3 * 8 + 4 * 4 + 2; static final int MAX_REQUEST_LENGTH = 100; static final int MAX_RESPONSE_LENGTH = 1500; static final int MAX_TIMEOUT = 15 * 8; // use the right factor to adjust it static final int DEFAULT_PORT = 80; private Thread thread; private Random random = new Random(); private DatagramSocket socket; private ByteBuffer request_body; private ByteBuffer request = ByteBuffer.allocate(MAX_REQUEST_LENGTH); private ByteBuffer response = ByteBuffer.allocate(MAX_RESPONSE_LENGTH); private boolean is_timeout; private boolean is_connection_error; private long updated_at; private Event last_event; private int timeStep = 1; private int transaction_id = -1; private long connection_id = -1; private long expire_time = 0; private URI tracker;
// Path: src/com/ndtorrent/client/ClientInfo.java // public interface ClientInfo { // // public String getID(); // // // public void getIP(); // // public int getPort(); // // // public void getKey(); // // public String getStorageLocation(); // // // public int maxOutgoingConnections(); // // // public int maxIncomingConnections(); // // } // Path: src/com/ndtorrent/client/tracker/UdpSession.java import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.SocketTimeoutException; import java.net.URI; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collection; import java.util.Random; import com.ndtorrent.client.ClientInfo; package com.ndtorrent.client.tracker; public final class UdpSession extends Session implements Runnable { // Implements the UDP tracker protocol static final long CONNECTION_ID = 0x41727101980L; static final int ACTION_CONNECT = 0; static final int ACTION_ANNOUNCE = 1; static final int ACTION_SCRAPE = 2; static final int ACTION_ERROR = 3; static final int ACTION_ERROR_LE = 0x03000000; static final int REQUEST_BODY_LENGTH = 2 * 20 + 3 * 8 + 4 * 4 + 2; static final int MAX_REQUEST_LENGTH = 100; static final int MAX_RESPONSE_LENGTH = 1500; static final int MAX_TIMEOUT = 15 * 8; // use the right factor to adjust it static final int DEFAULT_PORT = 80; private Thread thread; private Random random = new Random(); private DatagramSocket socket; private ByteBuffer request_body; private ByteBuffer request = ByteBuffer.allocate(MAX_REQUEST_LENGTH); private ByteBuffer response = ByteBuffer.allocate(MAX_RESPONSE_LENGTH); private boolean is_timeout; private boolean is_connection_error; private long updated_at; private Event last_event; private int timeStep = 1; private int transaction_id = -1; private long connection_id = -1; private long expire_time = 0; private URI tracker;
public UdpSession(String url, ClientInfo client_info, String info_hash) {
betroy/xifan
app/src/main/java/com/troy/xifan/view/XiFanClickableSpan.java
// Path: app/src/main/java/com/troy/xifan/App.java // public class App extends Application { // public static final String TAG = "Xifan"; // private static App sInstance; // // private UserRes user; // // private List<Activity> mActivityList = new ArrayList<>(); // // public App() { // sInstance = this; // } // // @Override // public void onCreate() { // super.onCreate(); // registerActivityLifecycleCallbacks(mActivityLifecycleCallbacks); // init(); // } // // private void init() { // Router.initialize(this); // // Stetho.initializeWithDefaults(this); // Logger.init(TAG) // default PRETTYLOGGER or use just init() // .methodCount(1) // default 2 // .hideThreadInfo() // default shown // .logLevel(LogLevel.FULL) // default LogLevel.FULL // .methodOffset(2); // default 0 // // FIR.init(this); // // 初始化参数依次为 this, AppId, AppKey // AVOSCloud.initialize(this, Constants.AVOSCloud.APP_ID, Constants.AVOSCloud.APP_KEY); // AVAnalytics.enableCrashReport(this, true); // } // // public static App getInstance() { // return sInstance; // } // // public UserRes getUser() { // return user; // } // // public void setUser(UserRes user) { // this.user = user; // } // // private ActivityLifecycleCallbacks mActivityLifecycleCallbacks = // new ActivityLifecycleCallbacks() { // @Override // public void onActivityCreated(Activity activity, Bundle savedInstanceState) { // if (!mActivityList.contains(activity)) { // mActivityList.add(activity); // } // } // // @Override // public void onActivityStarted(Activity activity) { // // } // // @Override // public void onActivityResumed(Activity activity) { // // } // // @Override // public void onActivityPaused(Activity activity) { // // } // // @Override // public void onActivityStopped(Activity activity) { // // } // // @Override // public void onActivitySaveInstanceState(Activity activity, Bundle outState) { // // } // // @Override // public void onActivityDestroyed(Activity activity) { // if (mActivityList.contains(activity)) { // mActivityList.remove(activity); // } // } // }; // // public List<Activity> getActivityList() { // return mActivityList; // } // // public void setActivityList(List<Activity> activityList) { // mActivityList = activityList; // } // // public void cleanActivityList() { // for (Activity activity : mActivityList) { // activity.finish(); // } // } // } // // Path: app/src/main/java/com/troy/xifan/activity/BrowserActivity.java // @Route({ Constants.Router.BROWSER, Constants.Router.SCHEME + Constants.Router.BROWSER }) // public class BrowserActivity extends BaseActivity { // public static final String BUNDLE_URL = "url"; // // @BindView(R.id.toolbar) Toolbar mToolbar; // @BindView(R.id.webview) WebView mWebView; // // private String mUrl; // // @Override // protected void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_borwser); // ButterKnife.bind(this); // Bundle bundle = getIntent().getExtras(); // if (bundle != null) { // mUrl = bundle.getString(BUNDLE_URL); // } // initViews(); // } // // @Override // protected void initViews() { // setSupportActionBar(mToolbar); // getSupportActionBar().setDisplayHomeAsUpEnabled(true); // // WebSettings webSettings = mWebView.getSettings(); // webSettings.setJavaScriptEnabled(true); // // mWebView.setWebViewClient(new WebViewClient() { // @Override // public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) { // view.loadUrl(request.getUrl().toString()); // return true; // } // }); // mWebView.setWebChromeClient(new WebChromeClient() { // @Override // public void onReceivedTitle(WebView view, String title) { // mToolbar.setTitle(title); // } // }); // if (!TextUtils.isEmpty(mUrl)) { // mWebView.loadUrl(mUrl); // } // } // // @Override // public boolean onOptionsItemSelected(MenuItem item) { // switch (item.getItemId()) { // case android.R.id.home: // finish(); // break; // } // return super.onOptionsItemSelected(item); // } // // @Override // public boolean onKeyDown(int keyCode, KeyEvent event) { // if (keyCode == KeyEvent.KEYCODE_BACK) { // if (mWebView.canGoBack()) { // mWebView.goBack(); // return true; // } else { // finish(); // } // } // return super.onKeyDown(keyCode, event); // } // }
import android.os.Bundle; import android.text.TextPaint; import android.text.style.ClickableSpan; import android.text.style.URLSpan; import android.view.View; import com.chenenyu.router.Router; import com.orhanobut.logger.Logger; import com.troy.xifan.App; import com.troy.xifan.R; import com.troy.xifan.activity.BrowserActivity;
package com.troy.xifan.view; /** * Created by chenlongfei on 2016/12/15. */ public class XiFanClickableSpan extends ClickableSpan { private URLSpan urlSpan; public XiFanClickableSpan(URLSpan urlSpan) { this.urlSpan = urlSpan; } @Override public void onClick(View view) { Logger.d("URL:" + urlSpan.getURL()); Bundle bundle = new Bundle();
// Path: app/src/main/java/com/troy/xifan/App.java // public class App extends Application { // public static final String TAG = "Xifan"; // private static App sInstance; // // private UserRes user; // // private List<Activity> mActivityList = new ArrayList<>(); // // public App() { // sInstance = this; // } // // @Override // public void onCreate() { // super.onCreate(); // registerActivityLifecycleCallbacks(mActivityLifecycleCallbacks); // init(); // } // // private void init() { // Router.initialize(this); // // Stetho.initializeWithDefaults(this); // Logger.init(TAG) // default PRETTYLOGGER or use just init() // .methodCount(1) // default 2 // .hideThreadInfo() // default shown // .logLevel(LogLevel.FULL) // default LogLevel.FULL // .methodOffset(2); // default 0 // // FIR.init(this); // // 初始化参数依次为 this, AppId, AppKey // AVOSCloud.initialize(this, Constants.AVOSCloud.APP_ID, Constants.AVOSCloud.APP_KEY); // AVAnalytics.enableCrashReport(this, true); // } // // public static App getInstance() { // return sInstance; // } // // public UserRes getUser() { // return user; // } // // public void setUser(UserRes user) { // this.user = user; // } // // private ActivityLifecycleCallbacks mActivityLifecycleCallbacks = // new ActivityLifecycleCallbacks() { // @Override // public void onActivityCreated(Activity activity, Bundle savedInstanceState) { // if (!mActivityList.contains(activity)) { // mActivityList.add(activity); // } // } // // @Override // public void onActivityStarted(Activity activity) { // // } // // @Override // public void onActivityResumed(Activity activity) { // // } // // @Override // public void onActivityPaused(Activity activity) { // // } // // @Override // public void onActivityStopped(Activity activity) { // // } // // @Override // public void onActivitySaveInstanceState(Activity activity, Bundle outState) { // // } // // @Override // public void onActivityDestroyed(Activity activity) { // if (mActivityList.contains(activity)) { // mActivityList.remove(activity); // } // } // }; // // public List<Activity> getActivityList() { // return mActivityList; // } // // public void setActivityList(List<Activity> activityList) { // mActivityList = activityList; // } // // public void cleanActivityList() { // for (Activity activity : mActivityList) { // activity.finish(); // } // } // } // // Path: app/src/main/java/com/troy/xifan/activity/BrowserActivity.java // @Route({ Constants.Router.BROWSER, Constants.Router.SCHEME + Constants.Router.BROWSER }) // public class BrowserActivity extends BaseActivity { // public static final String BUNDLE_URL = "url"; // // @BindView(R.id.toolbar) Toolbar mToolbar; // @BindView(R.id.webview) WebView mWebView; // // private String mUrl; // // @Override // protected void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_borwser); // ButterKnife.bind(this); // Bundle bundle = getIntent().getExtras(); // if (bundle != null) { // mUrl = bundle.getString(BUNDLE_URL); // } // initViews(); // } // // @Override // protected void initViews() { // setSupportActionBar(mToolbar); // getSupportActionBar().setDisplayHomeAsUpEnabled(true); // // WebSettings webSettings = mWebView.getSettings(); // webSettings.setJavaScriptEnabled(true); // // mWebView.setWebViewClient(new WebViewClient() { // @Override // public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) { // view.loadUrl(request.getUrl().toString()); // return true; // } // }); // mWebView.setWebChromeClient(new WebChromeClient() { // @Override // public void onReceivedTitle(WebView view, String title) { // mToolbar.setTitle(title); // } // }); // if (!TextUtils.isEmpty(mUrl)) { // mWebView.loadUrl(mUrl); // } // } // // @Override // public boolean onOptionsItemSelected(MenuItem item) { // switch (item.getItemId()) { // case android.R.id.home: // finish(); // break; // } // return super.onOptionsItemSelected(item); // } // // @Override // public boolean onKeyDown(int keyCode, KeyEvent event) { // if (keyCode == KeyEvent.KEYCODE_BACK) { // if (mWebView.canGoBack()) { // mWebView.goBack(); // return true; // } else { // finish(); // } // } // return super.onKeyDown(keyCode, event); // } // } // Path: app/src/main/java/com/troy/xifan/view/XiFanClickableSpan.java import android.os.Bundle; import android.text.TextPaint; import android.text.style.ClickableSpan; import android.text.style.URLSpan; import android.view.View; import com.chenenyu.router.Router; import com.orhanobut.logger.Logger; import com.troy.xifan.App; import com.troy.xifan.R; import com.troy.xifan.activity.BrowserActivity; package com.troy.xifan.view; /** * Created by chenlongfei on 2016/12/15. */ public class XiFanClickableSpan extends ClickableSpan { private URLSpan urlSpan; public XiFanClickableSpan(URLSpan urlSpan) { this.urlSpan = urlSpan; } @Override public void onClick(View view) { Logger.d("URL:" + urlSpan.getURL()); Bundle bundle = new Bundle();
bundle.putString(BrowserActivity.BUNDLE_URL, "http://www.baidu.com");
betroy/xifan
app/src/main/java/com/troy/xifan/model/request/User.java
// Path: app/src/main/java/com/troy/xifan/model/response/OAuthToken.java // public class OAuthToken implements Serializable { // private String oauthToken; // private String oauthTokenSecret; // // public OAuthToken(String oauthToken, String oauthTokenSecret) { // this.oauthToken = oauthToken; // this.oauthTokenSecret = oauthTokenSecret; // } // // public String getOauthToken() { // return oauthToken; // } // // public void setOauthToken(String oauthToken) { // this.oauthToken = oauthToken; // } // // public String getOauthTokenSecret() { // return oauthTokenSecret; // } // // public void setOauthTokenSecret(String oauthTokenSecret) { // this.oauthTokenSecret = oauthTokenSecret; // } // }
import com.troy.xifan.model.response.OAuthToken; import java.io.Serializable;
package com.troy.xifan.model.request; /** * Created by chenlongfei on 2016/11/24. */ public class User implements Serializable { private String userName; private String password;
// Path: app/src/main/java/com/troy/xifan/model/response/OAuthToken.java // public class OAuthToken implements Serializable { // private String oauthToken; // private String oauthTokenSecret; // // public OAuthToken(String oauthToken, String oauthTokenSecret) { // this.oauthToken = oauthToken; // this.oauthTokenSecret = oauthTokenSecret; // } // // public String getOauthToken() { // return oauthToken; // } // // public void setOauthToken(String oauthToken) { // this.oauthToken = oauthToken; // } // // public String getOauthTokenSecret() { // return oauthTokenSecret; // } // // public void setOauthTokenSecret(String oauthTokenSecret) { // this.oauthTokenSecret = oauthTokenSecret; // } // } // Path: app/src/main/java/com/troy/xifan/model/request/User.java import com.troy.xifan.model.response.OAuthToken; import java.io.Serializable; package com.troy.xifan.model.request; /** * Created by chenlongfei on 2016/11/24. */ public class User implements Serializable { private String userName; private String password;
private OAuthToken token;
betroy/xifan
app/src/main/java/com/troy/xifan/fragment/MessageFragment.java
// Path: app/src/main/java/com/troy/xifan/adapter/MessagePagerAdapter.java // public class MessagePagerAdapter extends FragmentPagerAdapter { // private List<Fragment> fragments; // private String[] tabTitles; // // public MessagePagerAdapter(FragmentManager fm, List<Fragment> fragments, String[] tabTitles) { // super(fm); // this.fragments = fragments; // this.tabTitles = tabTitles; // } // // @Override // public Fragment getItem(int position) { // return fragments.get(position); // } // // @Override // public int getCount() { // return fragments.size(); // } // // @Override // public CharSequence getPageTitle(int position) { // return tabTitles[position]; // } // }
import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.view.ViewPager; import android.support.v7.widget.Toolbar; import butterknife.BindView; import com.troy.xifan.R; import com.troy.xifan.adapter.MessagePagerAdapter; import java.util.ArrayList; import java.util.List;
package com.troy.xifan.fragment; /** * Created by chenlongfei on 2016/12/1. */ public class MessageFragment extends BaseFragment { @BindView(R.id.toolbar) Toolbar mToolbar; @BindView(R.id.tab_layout) TabLayout mTabLayout; @BindView(R.id.view_pager) ViewPager mViewPager; private List<Fragment> mFragments = new ArrayList<>(); private String[] mTabTitles; public static Fragment newInstance() { return new MessageFragment(); } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); initFragments(); } private void initFragments() { mFragments.add(MentionMessageFragment.newInstance()); mFragments.add(DirectMessageFragment.newInstance()); } @Override public void initViews() { mToolbar.setTitle(getString(R.string.title_message)); mTabTitles = new String[] { getString(R.string.title_tab_mention_msg), getString(R.string.title_tab_direct_msg) }; mTabLayout.setupWithViewPager(mViewPager); mViewPager.setOffscreenPageLimit(mTabTitles.length); mViewPager.setAdapter(
// Path: app/src/main/java/com/troy/xifan/adapter/MessagePagerAdapter.java // public class MessagePagerAdapter extends FragmentPagerAdapter { // private List<Fragment> fragments; // private String[] tabTitles; // // public MessagePagerAdapter(FragmentManager fm, List<Fragment> fragments, String[] tabTitles) { // super(fm); // this.fragments = fragments; // this.tabTitles = tabTitles; // } // // @Override // public Fragment getItem(int position) { // return fragments.get(position); // } // // @Override // public int getCount() { // return fragments.size(); // } // // @Override // public CharSequence getPageTitle(int position) { // return tabTitles[position]; // } // } // Path: app/src/main/java/com/troy/xifan/fragment/MessageFragment.java import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.view.ViewPager; import android.support.v7.widget.Toolbar; import butterknife.BindView; import com.troy.xifan.R; import com.troy.xifan.adapter.MessagePagerAdapter; import java.util.ArrayList; import java.util.List; package com.troy.xifan.fragment; /** * Created by chenlongfei on 2016/12/1. */ public class MessageFragment extends BaseFragment { @BindView(R.id.toolbar) Toolbar mToolbar; @BindView(R.id.tab_layout) TabLayout mTabLayout; @BindView(R.id.view_pager) ViewPager mViewPager; private List<Fragment> mFragments = new ArrayList<>(); private String[] mTabTitles; public static Fragment newInstance() { return new MessageFragment(); } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); initFragments(); } private void initFragments() { mFragments.add(MentionMessageFragment.newInstance()); mFragments.add(DirectMessageFragment.newInstance()); } @Override public void initViews() { mToolbar.setTitle(getString(R.string.title_message)); mTabTitles = new String[] { getString(R.string.title_tab_mention_msg), getString(R.string.title_tab_direct_msg) }; mTabLayout.setupWithViewPager(mViewPager); mViewPager.setOffscreenPageLimit(mTabTitles.length); mViewPager.setAdapter(
new MessagePagerAdapter(getChildFragmentManager(), mFragments, mTabTitles));
betroy/xifan
app/src/main/java/com/troy/xifan/http/callback/SimpleHttpRequestCallback.java
// Path: app/src/main/java/com/troy/xifan/http/exception/ApiException.java // public class ApiException extends Exception { // private String errorCode; // private String errorMessage; // // public ApiException(String errorCode, String errorMessage) { // this.errorCode = errorCode; // this.errorMessage = errorMessage; // } // // public String getErrorCode() { // return errorCode; // } // // public void setErrorCode(String errorCode) { // this.errorCode = errorCode; // } // // public String getErrorMessage() { // return errorMessage; // } // // public void setErrorMessage(String errorMessage) { // this.errorMessage = errorMessage; // } // }
import com.troy.xifan.http.exception.ApiException;
package com.troy.xifan.http.callback; /** * Created by chenlongfei on 2017/1/7. */ public class SimpleHttpRequestCallback<T> implements HttpRequestCallback<T> { @Override public void onStart() { } @Override public void onSuccess(T responseData) { } @Override
// Path: app/src/main/java/com/troy/xifan/http/exception/ApiException.java // public class ApiException extends Exception { // private String errorCode; // private String errorMessage; // // public ApiException(String errorCode, String errorMessage) { // this.errorCode = errorCode; // this.errorMessage = errorMessage; // } // // public String getErrorCode() { // return errorCode; // } // // public void setErrorCode(String errorCode) { // this.errorCode = errorCode; // } // // public String getErrorMessage() { // return errorMessage; // } // // public void setErrorMessage(String errorMessage) { // this.errorMessage = errorMessage; // } // } // Path: app/src/main/java/com/troy/xifan/http/callback/SimpleHttpRequestCallback.java import com.troy.xifan.http.exception.ApiException; package com.troy.xifan.http.callback; /** * Created by chenlongfei on 2017/1/7. */ public class SimpleHttpRequestCallback<T> implements HttpRequestCallback<T> { @Override public void onStart() { } @Override public void onSuccess(T responseData) { } @Override
public void onFail(ApiException apiException) {
betroy/xifan
app/src/main/java/com/troy/xifan/http/callback/HttpRequestCallback.java
// Path: app/src/main/java/com/troy/xifan/http/exception/ApiException.java // public class ApiException extends Exception { // private String errorCode; // private String errorMessage; // // public ApiException(String errorCode, String errorMessage) { // this.errorCode = errorCode; // this.errorMessage = errorMessage; // } // // public String getErrorCode() { // return errorCode; // } // // public void setErrorCode(String errorCode) { // this.errorCode = errorCode; // } // // public String getErrorMessage() { // return errorMessage; // } // // public void setErrorMessage(String errorMessage) { // this.errorMessage = errorMessage; // } // }
import com.troy.xifan.http.exception.ApiException;
package com.troy.xifan.http.callback; /** * Created by chenlongfei on 2016/11/19. */ public interface HttpRequestCallback<T> { void onStart(); void onSuccess(T responseData);
// Path: app/src/main/java/com/troy/xifan/http/exception/ApiException.java // public class ApiException extends Exception { // private String errorCode; // private String errorMessage; // // public ApiException(String errorCode, String errorMessage) { // this.errorCode = errorCode; // this.errorMessage = errorMessage; // } // // public String getErrorCode() { // return errorCode; // } // // public void setErrorCode(String errorCode) { // this.errorCode = errorCode; // } // // public String getErrorMessage() { // return errorMessage; // } // // public void setErrorMessage(String errorMessage) { // this.errorMessage = errorMessage; // } // } // Path: app/src/main/java/com/troy/xifan/http/callback/HttpRequestCallback.java import com.troy.xifan.http.exception.ApiException; package com.troy.xifan.http.callback; /** * Created by chenlongfei on 2016/11/19. */ public interface HttpRequestCallback<T> { void onStart(); void onSuccess(T responseData);
void onFail(ApiException apiException);
betroy/xifan
app/src/main/java/com/troy/xifan/util/FileUtils.java
// Path: app/src/main/java/com/troy/xifan/App.java // public class App extends Application { // public static final String TAG = "Xifan"; // private static App sInstance; // // private UserRes user; // // private List<Activity> mActivityList = new ArrayList<>(); // // public App() { // sInstance = this; // } // // @Override // public void onCreate() { // super.onCreate(); // registerActivityLifecycleCallbacks(mActivityLifecycleCallbacks); // init(); // } // // private void init() { // Router.initialize(this); // // Stetho.initializeWithDefaults(this); // Logger.init(TAG) // default PRETTYLOGGER or use just init() // .methodCount(1) // default 2 // .hideThreadInfo() // default shown // .logLevel(LogLevel.FULL) // default LogLevel.FULL // .methodOffset(2); // default 0 // // FIR.init(this); // // 初始化参数依次为 this, AppId, AppKey // AVOSCloud.initialize(this, Constants.AVOSCloud.APP_ID, Constants.AVOSCloud.APP_KEY); // AVAnalytics.enableCrashReport(this, true); // } // // public static App getInstance() { // return sInstance; // } // // public UserRes getUser() { // return user; // } // // public void setUser(UserRes user) { // this.user = user; // } // // private ActivityLifecycleCallbacks mActivityLifecycleCallbacks = // new ActivityLifecycleCallbacks() { // @Override // public void onActivityCreated(Activity activity, Bundle savedInstanceState) { // if (!mActivityList.contains(activity)) { // mActivityList.add(activity); // } // } // // @Override // public void onActivityStarted(Activity activity) { // // } // // @Override // public void onActivityResumed(Activity activity) { // // } // // @Override // public void onActivityPaused(Activity activity) { // // } // // @Override // public void onActivityStopped(Activity activity) { // // } // // @Override // public void onActivitySaveInstanceState(Activity activity, Bundle outState) { // // } // // @Override // public void onActivityDestroyed(Activity activity) { // if (mActivityList.contains(activity)) { // mActivityList.remove(activity); // } // } // }; // // public List<Activity> getActivityList() { // return mActivityList; // } // // public void setActivityList(List<Activity> activityList) { // mActivityList = activityList; // } // // public void cleanActivityList() { // for (Activity activity : mActivityList) { // activity.finish(); // } // } // }
import android.os.Environment; import com.orhanobut.logger.Logger; import com.troy.xifan.App; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream;
public synchronized static Object readObjectFromFile(File file) { ObjectInputStream input = null; Object object = null; try { input = new ObjectInputStream(new FileInputStream(file)); object = input.readObject(); } catch (IOException e) { e.printStackTrace(); Logger.e("read object from file fail\n" + e); } catch (ClassNotFoundException e) { e.printStackTrace(); Logger.e("read object from file fail\n" + e); } finally { try { if (input != null) { input.close(); } } catch (IOException e) { e.printStackTrace(); } } return object; } public static boolean deleteFile(File file) { return file.delete(); } public static File getCacheFile(String fileName) {
// Path: app/src/main/java/com/troy/xifan/App.java // public class App extends Application { // public static final String TAG = "Xifan"; // private static App sInstance; // // private UserRes user; // // private List<Activity> mActivityList = new ArrayList<>(); // // public App() { // sInstance = this; // } // // @Override // public void onCreate() { // super.onCreate(); // registerActivityLifecycleCallbacks(mActivityLifecycleCallbacks); // init(); // } // // private void init() { // Router.initialize(this); // // Stetho.initializeWithDefaults(this); // Logger.init(TAG) // default PRETTYLOGGER or use just init() // .methodCount(1) // default 2 // .hideThreadInfo() // default shown // .logLevel(LogLevel.FULL) // default LogLevel.FULL // .methodOffset(2); // default 0 // // FIR.init(this); // // 初始化参数依次为 this, AppId, AppKey // AVOSCloud.initialize(this, Constants.AVOSCloud.APP_ID, Constants.AVOSCloud.APP_KEY); // AVAnalytics.enableCrashReport(this, true); // } // // public static App getInstance() { // return sInstance; // } // // public UserRes getUser() { // return user; // } // // public void setUser(UserRes user) { // this.user = user; // } // // private ActivityLifecycleCallbacks mActivityLifecycleCallbacks = // new ActivityLifecycleCallbacks() { // @Override // public void onActivityCreated(Activity activity, Bundle savedInstanceState) { // if (!mActivityList.contains(activity)) { // mActivityList.add(activity); // } // } // // @Override // public void onActivityStarted(Activity activity) { // // } // // @Override // public void onActivityResumed(Activity activity) { // // } // // @Override // public void onActivityPaused(Activity activity) { // // } // // @Override // public void onActivityStopped(Activity activity) { // // } // // @Override // public void onActivitySaveInstanceState(Activity activity, Bundle outState) { // // } // // @Override // public void onActivityDestroyed(Activity activity) { // if (mActivityList.contains(activity)) { // mActivityList.remove(activity); // } // } // }; // // public List<Activity> getActivityList() { // return mActivityList; // } // // public void setActivityList(List<Activity> activityList) { // mActivityList = activityList; // } // // public void cleanActivityList() { // for (Activity activity : mActivityList) { // activity.finish(); // } // } // } // Path: app/src/main/java/com/troy/xifan/util/FileUtils.java import android.os.Environment; import com.orhanobut.logger.Logger; import com.troy.xifan.App; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; public synchronized static Object readObjectFromFile(File file) { ObjectInputStream input = null; Object object = null; try { input = new ObjectInputStream(new FileInputStream(file)); object = input.readObject(); } catch (IOException e) { e.printStackTrace(); Logger.e("read object from file fail\n" + e); } catch (ClassNotFoundException e) { e.printStackTrace(); Logger.e("read object from file fail\n" + e); } finally { try { if (input != null) { input.close(); } } catch (IOException e) { e.printStackTrace(); } } return object; } public static boolean deleteFile(File file) { return file.delete(); } public static File getCacheFile(String fileName) {
File dir = App.getInstance().getCacheDir();
betroy/xifan
app/src/main/java/com/troy/xifan/http/exception/ExceptionHandle.java
// Path: app/src/main/java/com/troy/xifan/App.java // public class App extends Application { // public static final String TAG = "Xifan"; // private static App sInstance; // // private UserRes user; // // private List<Activity> mActivityList = new ArrayList<>(); // // public App() { // sInstance = this; // } // // @Override // public void onCreate() { // super.onCreate(); // registerActivityLifecycleCallbacks(mActivityLifecycleCallbacks); // init(); // } // // private void init() { // Router.initialize(this); // // Stetho.initializeWithDefaults(this); // Logger.init(TAG) // default PRETTYLOGGER or use just init() // .methodCount(1) // default 2 // .hideThreadInfo() // default shown // .logLevel(LogLevel.FULL) // default LogLevel.FULL // .methodOffset(2); // default 0 // // FIR.init(this); // // 初始化参数依次为 this, AppId, AppKey // AVOSCloud.initialize(this, Constants.AVOSCloud.APP_ID, Constants.AVOSCloud.APP_KEY); // AVAnalytics.enableCrashReport(this, true); // } // // public static App getInstance() { // return sInstance; // } // // public UserRes getUser() { // return user; // } // // public void setUser(UserRes user) { // this.user = user; // } // // private ActivityLifecycleCallbacks mActivityLifecycleCallbacks = // new ActivityLifecycleCallbacks() { // @Override // public void onActivityCreated(Activity activity, Bundle savedInstanceState) { // if (!mActivityList.contains(activity)) { // mActivityList.add(activity); // } // } // // @Override // public void onActivityStarted(Activity activity) { // // } // // @Override // public void onActivityResumed(Activity activity) { // // } // // @Override // public void onActivityPaused(Activity activity) { // // } // // @Override // public void onActivityStopped(Activity activity) { // // } // // @Override // public void onActivitySaveInstanceState(Activity activity, Bundle outState) { // // } // // @Override // public void onActivityDestroyed(Activity activity) { // if (mActivityList.contains(activity)) { // mActivityList.remove(activity); // } // } // }; // // public List<Activity> getActivityList() { // return mActivityList; // } // // public void setActivityList(List<Activity> activityList) { // mActivityList = activityList; // } // // public void cleanActivityList() { // for (Activity activity : mActivityList) { // activity.finish(); // } // } // }
import android.content.Context; import android.text.TextUtils; import com.google.gson.JsonParseException; import com.google.gson.JsonSyntaxException; import com.orhanobut.logger.Logger; import com.troy.xifan.App; import com.troy.xifan.R; import java.io.IOException; import java.net.ConnectException; import java.net.SocketTimeoutException; import retrofit2.adapter.rxjava.HttpException;
package com.troy.xifan.http.exception; /** * Created by chenlongfei on 2016/11/27. */ public class ExceptionHandle { //HTTP状态码 private static final int UNAUTHORIZED = 401; private static final int FORBIDDEN = 403; private static final int NOT_FOUND = 404; private static final int REQUEST_TIMEOUT = 408; private static final int RANGE_NOT_SATISFIABLE = 416; private static final int INTERNAL_SERVER_ERROR = 500; private static final int BAD_GATEWAY = 502; private static final int SERVICE_UNAVAILABLE = 503; private static final int GATEWAY_TIMEOUT = 504; public static ApiException handleException(Throwable e) { e.printStackTrace(); Logger.e("http request error result:\n" + e.fillInStackTrace());
// Path: app/src/main/java/com/troy/xifan/App.java // public class App extends Application { // public static final String TAG = "Xifan"; // private static App sInstance; // // private UserRes user; // // private List<Activity> mActivityList = new ArrayList<>(); // // public App() { // sInstance = this; // } // // @Override // public void onCreate() { // super.onCreate(); // registerActivityLifecycleCallbacks(mActivityLifecycleCallbacks); // init(); // } // // private void init() { // Router.initialize(this); // // Stetho.initializeWithDefaults(this); // Logger.init(TAG) // default PRETTYLOGGER or use just init() // .methodCount(1) // default 2 // .hideThreadInfo() // default shown // .logLevel(LogLevel.FULL) // default LogLevel.FULL // .methodOffset(2); // default 0 // // FIR.init(this); // // 初始化参数依次为 this, AppId, AppKey // AVOSCloud.initialize(this, Constants.AVOSCloud.APP_ID, Constants.AVOSCloud.APP_KEY); // AVAnalytics.enableCrashReport(this, true); // } // // public static App getInstance() { // return sInstance; // } // // public UserRes getUser() { // return user; // } // // public void setUser(UserRes user) { // this.user = user; // } // // private ActivityLifecycleCallbacks mActivityLifecycleCallbacks = // new ActivityLifecycleCallbacks() { // @Override // public void onActivityCreated(Activity activity, Bundle savedInstanceState) { // if (!mActivityList.contains(activity)) { // mActivityList.add(activity); // } // } // // @Override // public void onActivityStarted(Activity activity) { // // } // // @Override // public void onActivityResumed(Activity activity) { // // } // // @Override // public void onActivityPaused(Activity activity) { // // } // // @Override // public void onActivityStopped(Activity activity) { // // } // // @Override // public void onActivitySaveInstanceState(Activity activity, Bundle outState) { // // } // // @Override // public void onActivityDestroyed(Activity activity) { // if (mActivityList.contains(activity)) { // mActivityList.remove(activity); // } // } // }; // // public List<Activity> getActivityList() { // return mActivityList; // } // // public void setActivityList(List<Activity> activityList) { // mActivityList = activityList; // } // // public void cleanActivityList() { // for (Activity activity : mActivityList) { // activity.finish(); // } // } // } // Path: app/src/main/java/com/troy/xifan/http/exception/ExceptionHandle.java import android.content.Context; import android.text.TextUtils; import com.google.gson.JsonParseException; import com.google.gson.JsonSyntaxException; import com.orhanobut.logger.Logger; import com.troy.xifan.App; import com.troy.xifan.R; import java.io.IOException; import java.net.ConnectException; import java.net.SocketTimeoutException; import retrofit2.adapter.rxjava.HttpException; package com.troy.xifan.http.exception; /** * Created by chenlongfei on 2016/11/27. */ public class ExceptionHandle { //HTTP状态码 private static final int UNAUTHORIZED = 401; private static final int FORBIDDEN = 403; private static final int NOT_FOUND = 404; private static final int REQUEST_TIMEOUT = 408; private static final int RANGE_NOT_SATISFIABLE = 416; private static final int INTERNAL_SERVER_ERROR = 500; private static final int BAD_GATEWAY = 502; private static final int SERVICE_UNAVAILABLE = 503; private static final int GATEWAY_TIMEOUT = 504; public static ApiException handleException(Throwable e) { e.printStackTrace(); Logger.e("http request error result:\n" + e.fillInStackTrace());
Context context = App.getInstance().getApplicationContext();
apache/maven-enforcer
enforcer-rules/src/main/java/org/apache/maven/plugins/enforcer/RequireNoRepositories.java
// Path: enforcer-api/src/main/java/org/apache/maven/enforcer/rule/api/EnforcerRuleHelper.java // public interface EnforcerRuleHelper // extends ExpressionEvaluator // { // // /** // * Gets the log. // * // * @return the log // */ // @Nonnull // Log getLog (); // // /** // * Gets the component. // * // * @param clazz the clazz // * // * @return the component // * // * @throws ComponentLookupException the component lookup exception // */ // @Nonnull // <T> T getComponent ( Class<T> clazz ) // throws ComponentLookupException; // // /** // * Gets the component. // * // * @param componentKey the component key // * // * @return the component // * // * @throws ComponentLookupException the component lookup exception // */ // @Nonnull // Object getComponent ( String componentKey ) // throws ComponentLookupException; // // /** // * Gets the component. // * // * @param role the role // * @param roleHint the role hint // * // * @return the component // * // * @throws ComponentLookupException the component lookup exception // */ // Object getComponent ( String role, String roleHint ) // throws ComponentLookupException; // // /** // * Gets the component. // * // * @param clazz the clazz // * @param roleHint the role hint // * // * @return the component // * // * @throws ComponentLookupException the component lookup exception // */ // <T> T getComponent ( Class<T> clazz, String roleHint ) // throws ComponentLookupException; // // /** // * Gets the component map. // * // * @param role the role // * // * @return the component map // * // * @throws ComponentLookupException the component lookup exception // */ // Map<String, ?> getComponentMap ( String role ) // throws ComponentLookupException; // // /** // * Gets the component list. // * // * @param role the role // * // * @return the component list // * // * @throws ComponentLookupException the component lookup exception // */ // List<?> getComponentList ( String role ) // throws ComponentLookupException; // // /** // * Gets the container. // * // * @return the container // */ // PlexusContainer getContainer(); // }
import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluationException; import org.codehaus.plexus.util.StringUtils; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.apache.maven.enforcer.rule.api.EnforcerRuleException; import org.apache.maven.enforcer.rule.api.EnforcerRuleHelper; import org.apache.maven.execution.MavenSession; import org.apache.maven.model.Model; import org.apache.maven.model.Repository; import org.apache.maven.plugin.logging.Log; import org.apache.maven.project.MavenProject;
{ this.banRepositories = banRepositories; } public final void setBanPluginRepositories( boolean banPluginRepositories ) { this.banPluginRepositories = banPluginRepositories; } public final void setAllowedRepositories( List<String> allowedRepositories ) { this.allowedRepositories = allowedRepositories; } public final void setAllowedPluginRepositories( List<String> allowedPluginRepositories ) { this.allowedPluginRepositories = allowedPluginRepositories; } public final void setAllowSnapshotRepositories( boolean allowSnapshotRepositories ) { this.allowSnapshotRepositories = allowSnapshotRepositories; } public final void setAllowSnapshotPluginRepositories( boolean allowSnapshotPluginRepositories ) { this.allowSnapshotPluginRepositories = allowSnapshotPluginRepositories; } @Override
// Path: enforcer-api/src/main/java/org/apache/maven/enforcer/rule/api/EnforcerRuleHelper.java // public interface EnforcerRuleHelper // extends ExpressionEvaluator // { // // /** // * Gets the log. // * // * @return the log // */ // @Nonnull // Log getLog (); // // /** // * Gets the component. // * // * @param clazz the clazz // * // * @return the component // * // * @throws ComponentLookupException the component lookup exception // */ // @Nonnull // <T> T getComponent ( Class<T> clazz ) // throws ComponentLookupException; // // /** // * Gets the component. // * // * @param componentKey the component key // * // * @return the component // * // * @throws ComponentLookupException the component lookup exception // */ // @Nonnull // Object getComponent ( String componentKey ) // throws ComponentLookupException; // // /** // * Gets the component. // * // * @param role the role // * @param roleHint the role hint // * // * @return the component // * // * @throws ComponentLookupException the component lookup exception // */ // Object getComponent ( String role, String roleHint ) // throws ComponentLookupException; // // /** // * Gets the component. // * // * @param clazz the clazz // * @param roleHint the role hint // * // * @return the component // * // * @throws ComponentLookupException the component lookup exception // */ // <T> T getComponent ( Class<T> clazz, String roleHint ) // throws ComponentLookupException; // // /** // * Gets the component map. // * // * @param role the role // * // * @return the component map // * // * @throws ComponentLookupException the component lookup exception // */ // Map<String, ?> getComponentMap ( String role ) // throws ComponentLookupException; // // /** // * Gets the component list. // * // * @param role the role // * // * @return the component list // * // * @throws ComponentLookupException the component lookup exception // */ // List<?> getComponentList ( String role ) // throws ComponentLookupException; // // /** // * Gets the container. // * // * @return the container // */ // PlexusContainer getContainer(); // } // Path: enforcer-rules/src/main/java/org/apache/maven/plugins/enforcer/RequireNoRepositories.java import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluationException; import org.codehaus.plexus.util.StringUtils; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.apache.maven.enforcer.rule.api.EnforcerRuleException; import org.apache.maven.enforcer.rule.api.EnforcerRuleHelper; import org.apache.maven.execution.MavenSession; import org.apache.maven.model.Model; import org.apache.maven.model.Repository; import org.apache.maven.plugin.logging.Log; import org.apache.maven.project.MavenProject; { this.banRepositories = banRepositories; } public final void setBanPluginRepositories( boolean banPluginRepositories ) { this.banPluginRepositories = banPluginRepositories; } public final void setAllowedRepositories( List<String> allowedRepositories ) { this.allowedRepositories = allowedRepositories; } public final void setAllowedPluginRepositories( List<String> allowedPluginRepositories ) { this.allowedPluginRepositories = allowedPluginRepositories; } public final void setAllowSnapshotRepositories( boolean allowSnapshotRepositories ) { this.allowSnapshotRepositories = allowSnapshotRepositories; } public final void setAllowSnapshotPluginRepositories( boolean allowSnapshotPluginRepositories ) { this.allowSnapshotPluginRepositories = allowSnapshotPluginRepositories; } @Override
public void execute( EnforcerRuleHelper helper )
apache/maven-enforcer
enforcer-rules/src/main/java/org/apache/maven/plugins/enforcer/AlwaysPass.java
// Path: enforcer-api/src/main/java/org/apache/maven/enforcer/rule/api/EnforcerRuleHelper.java // public interface EnforcerRuleHelper // extends ExpressionEvaluator // { // // /** // * Gets the log. // * // * @return the log // */ // @Nonnull // Log getLog (); // // /** // * Gets the component. // * // * @param clazz the clazz // * // * @return the component // * // * @throws ComponentLookupException the component lookup exception // */ // @Nonnull // <T> T getComponent ( Class<T> clazz ) // throws ComponentLookupException; // // /** // * Gets the component. // * // * @param componentKey the component key // * // * @return the component // * // * @throws ComponentLookupException the component lookup exception // */ // @Nonnull // Object getComponent ( String componentKey ) // throws ComponentLookupException; // // /** // * Gets the component. // * // * @param role the role // * @param roleHint the role hint // * // * @return the component // * // * @throws ComponentLookupException the component lookup exception // */ // Object getComponent ( String role, String roleHint ) // throws ComponentLookupException; // // /** // * Gets the component. // * // * @param clazz the clazz // * @param roleHint the role hint // * // * @return the component // * // * @throws ComponentLookupException the component lookup exception // */ // <T> T getComponent ( Class<T> clazz, String roleHint ) // throws ComponentLookupException; // // /** // * Gets the component map. // * // * @param role the role // * // * @return the component map // * // * @throws ComponentLookupException the component lookup exception // */ // Map<String, ?> getComponentMap ( String role ) // throws ComponentLookupException; // // /** // * Gets the component list. // * // * @param role the role // * // * @return the component list // * // * @throws ComponentLookupException the component lookup exception // */ // List<?> getComponentList ( String role ) // throws ComponentLookupException; // // /** // * Gets the container. // * // * @return the container // */ // PlexusContainer getContainer(); // }
import org.apache.maven.enforcer.rule.api.EnforcerRuleException; import org.apache.maven.enforcer.rule.api.EnforcerRuleHelper; import org.apache.maven.plugin.logging.Log;
package org.apache.maven.plugins.enforcer; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /** * Always pass. This rule is useful for testing the Enforcer configuration. * @author Ben Lidgey */ public class AlwaysPass extends AbstractNonCacheableEnforcerRule { @Override
// Path: enforcer-api/src/main/java/org/apache/maven/enforcer/rule/api/EnforcerRuleHelper.java // public interface EnforcerRuleHelper // extends ExpressionEvaluator // { // // /** // * Gets the log. // * // * @return the log // */ // @Nonnull // Log getLog (); // // /** // * Gets the component. // * // * @param clazz the clazz // * // * @return the component // * // * @throws ComponentLookupException the component lookup exception // */ // @Nonnull // <T> T getComponent ( Class<T> clazz ) // throws ComponentLookupException; // // /** // * Gets the component. // * // * @param componentKey the component key // * // * @return the component // * // * @throws ComponentLookupException the component lookup exception // */ // @Nonnull // Object getComponent ( String componentKey ) // throws ComponentLookupException; // // /** // * Gets the component. // * // * @param role the role // * @param roleHint the role hint // * // * @return the component // * // * @throws ComponentLookupException the component lookup exception // */ // Object getComponent ( String role, String roleHint ) // throws ComponentLookupException; // // /** // * Gets the component. // * // * @param clazz the clazz // * @param roleHint the role hint // * // * @return the component // * // * @throws ComponentLookupException the component lookup exception // */ // <T> T getComponent ( Class<T> clazz, String roleHint ) // throws ComponentLookupException; // // /** // * Gets the component map. // * // * @param role the role // * // * @return the component map // * // * @throws ComponentLookupException the component lookup exception // */ // Map<String, ?> getComponentMap ( String role ) // throws ComponentLookupException; // // /** // * Gets the component list. // * // * @param role the role // * // * @return the component list // * // * @throws ComponentLookupException the component lookup exception // */ // List<?> getComponentList ( String role ) // throws ComponentLookupException; // // /** // * Gets the container. // * // * @return the container // */ // PlexusContainer getContainer(); // } // Path: enforcer-rules/src/main/java/org/apache/maven/plugins/enforcer/AlwaysPass.java import org.apache.maven.enforcer.rule.api.EnforcerRuleException; import org.apache.maven.enforcer.rule.api.EnforcerRuleHelper; import org.apache.maven.plugin.logging.Log; package org.apache.maven.plugins.enforcer; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /** * Always pass. This rule is useful for testing the Enforcer configuration. * @author Ben Lidgey */ public class AlwaysPass extends AbstractNonCacheableEnforcerRule { @Override
public void execute( EnforcerRuleHelper helper )
apache/maven-enforcer
enforcer-rules/src/main/java/org/apache/maven/plugins/enforcer/BanDuplicatePomDependencyVersions.java
// Path: enforcer-api/src/main/java/org/apache/maven/enforcer/rule/api/EnforcerRuleHelper.java // public interface EnforcerRuleHelper // extends ExpressionEvaluator // { // // /** // * Gets the log. // * // * @return the log // */ // @Nonnull // Log getLog (); // // /** // * Gets the component. // * // * @param clazz the clazz // * // * @return the component // * // * @throws ComponentLookupException the component lookup exception // */ // @Nonnull // <T> T getComponent ( Class<T> clazz ) // throws ComponentLookupException; // // /** // * Gets the component. // * // * @param componentKey the component key // * // * @return the component // * // * @throws ComponentLookupException the component lookup exception // */ // @Nonnull // Object getComponent ( String componentKey ) // throws ComponentLookupException; // // /** // * Gets the component. // * // * @param role the role // * @param roleHint the role hint // * // * @return the component // * // * @throws ComponentLookupException the component lookup exception // */ // Object getComponent ( String role, String roleHint ) // throws ComponentLookupException; // // /** // * Gets the component. // * // * @param clazz the clazz // * @param roleHint the role hint // * // * @return the component // * // * @throws ComponentLookupException the component lookup exception // */ // <T> T getComponent ( Class<T> clazz, String roleHint ) // throws ComponentLookupException; // // /** // * Gets the component map. // * // * @param role the role // * // * @return the component map // * // * @throws ComponentLookupException the component lookup exception // */ // Map<String, ?> getComponentMap ( String role ) // throws ComponentLookupException; // // /** // * Gets the component list. // * // * @param role the role // * // * @return the component list // * // * @throws ComponentLookupException the component lookup exception // */ // List<?> getComponentList ( String role ) // throws ComponentLookupException; // // /** // * Gets the container. // * // * @return the container // */ // PlexusContainer getContainer(); // }
import org.apache.maven.model.Model; import org.apache.maven.model.Profile; import org.apache.maven.model.io.xpp3.MavenXpp3Reader; import org.apache.maven.project.MavenProject; import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluationException; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; import java.io.FileInputStream; import java.io.IOException; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.maven.enforcer.rule.api.EnforcerRuleException; import org.apache.maven.enforcer.rule.api.EnforcerRuleHelper; import org.apache.maven.model.Dependency;
package org.apache.maven.plugins.enforcer; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /** * Since Maven 3 'dependencies.dependency.(groupId:artifactId:type:classifier)' must be unique. Early versions of Maven * 3 already warn, this rule can force to break a build for this reason. * * @author Robert Scholte * @since 1.3 */ public class BanDuplicatePomDependencyVersions extends AbstractNonCacheableEnforcerRule { @Override
// Path: enforcer-api/src/main/java/org/apache/maven/enforcer/rule/api/EnforcerRuleHelper.java // public interface EnforcerRuleHelper // extends ExpressionEvaluator // { // // /** // * Gets the log. // * // * @return the log // */ // @Nonnull // Log getLog (); // // /** // * Gets the component. // * // * @param clazz the clazz // * // * @return the component // * // * @throws ComponentLookupException the component lookup exception // */ // @Nonnull // <T> T getComponent ( Class<T> clazz ) // throws ComponentLookupException; // // /** // * Gets the component. // * // * @param componentKey the component key // * // * @return the component // * // * @throws ComponentLookupException the component lookup exception // */ // @Nonnull // Object getComponent ( String componentKey ) // throws ComponentLookupException; // // /** // * Gets the component. // * // * @param role the role // * @param roleHint the role hint // * // * @return the component // * // * @throws ComponentLookupException the component lookup exception // */ // Object getComponent ( String role, String roleHint ) // throws ComponentLookupException; // // /** // * Gets the component. // * // * @param clazz the clazz // * @param roleHint the role hint // * // * @return the component // * // * @throws ComponentLookupException the component lookup exception // */ // <T> T getComponent ( Class<T> clazz, String roleHint ) // throws ComponentLookupException; // // /** // * Gets the component map. // * // * @param role the role // * // * @return the component map // * // * @throws ComponentLookupException the component lookup exception // */ // Map<String, ?> getComponentMap ( String role ) // throws ComponentLookupException; // // /** // * Gets the component list. // * // * @param role the role // * // * @return the component list // * // * @throws ComponentLookupException the component lookup exception // */ // List<?> getComponentList ( String role ) // throws ComponentLookupException; // // /** // * Gets the container. // * // * @return the container // */ // PlexusContainer getContainer(); // } // Path: enforcer-rules/src/main/java/org/apache/maven/plugins/enforcer/BanDuplicatePomDependencyVersions.java import org.apache.maven.model.Model; import org.apache.maven.model.Profile; import org.apache.maven.model.io.xpp3.MavenXpp3Reader; import org.apache.maven.project.MavenProject; import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluationException; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; import java.io.FileInputStream; import java.io.IOException; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.maven.enforcer.rule.api.EnforcerRuleException; import org.apache.maven.enforcer.rule.api.EnforcerRuleHelper; import org.apache.maven.model.Dependency; package org.apache.maven.plugins.enforcer; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /** * Since Maven 3 'dependencies.dependency.(groupId:artifactId:type:classifier)' must be unique. Early versions of Maven * 3 already warn, this rule can force to break a build for this reason. * * @author Robert Scholte * @since 1.3 */ public class BanDuplicatePomDependencyVersions extends AbstractNonCacheableEnforcerRule { @Override
public void execute( EnforcerRuleHelper helper )
apache/maven-enforcer
enforcer-rules/src/main/java/org/apache/maven/plugins/enforcer/RequireActiveProfile.java
// Path: enforcer-api/src/main/java/org/apache/maven/enforcer/rule/api/EnforcerRuleHelper.java // public interface EnforcerRuleHelper // extends ExpressionEvaluator // { // // /** // * Gets the log. // * // * @return the log // */ // @Nonnull // Log getLog (); // // /** // * Gets the component. // * // * @param clazz the clazz // * // * @return the component // * // * @throws ComponentLookupException the component lookup exception // */ // @Nonnull // <T> T getComponent ( Class<T> clazz ) // throws ComponentLookupException; // // /** // * Gets the component. // * // * @param componentKey the component key // * // * @return the component // * // * @throws ComponentLookupException the component lookup exception // */ // @Nonnull // Object getComponent ( String componentKey ) // throws ComponentLookupException; // // /** // * Gets the component. // * // * @param role the role // * @param roleHint the role hint // * // * @return the component // * // * @throws ComponentLookupException the component lookup exception // */ // Object getComponent ( String role, String roleHint ) // throws ComponentLookupException; // // /** // * Gets the component. // * // * @param clazz the clazz // * @param roleHint the role hint // * // * @return the component // * // * @throws ComponentLookupException the component lookup exception // */ // <T> T getComponent ( Class<T> clazz, String roleHint ) // throws ComponentLookupException; // // /** // * Gets the component map. // * // * @param role the role // * // * @return the component map // * // * @throws ComponentLookupException the component lookup exception // */ // Map<String, ?> getComponentMap ( String role ) // throws ComponentLookupException; // // /** // * Gets the component list. // * // * @param role the role // * // * @return the component list // * // * @throws ComponentLookupException the component lookup exception // */ // List<?> getComponentList ( String role ) // throws ComponentLookupException; // // /** // * Gets the container. // * // * @return the container // */ // PlexusContainer getContainer(); // }
import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.maven.enforcer.rule.api.EnforcerRuleException; import org.apache.maven.enforcer.rule.api.EnforcerRuleHelper; import org.apache.maven.project.MavenProject; import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluationException; import org.codehaus.plexus.util.StringUtils;
package org.apache.maven.plugins.enforcer; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /** * This rule checks that some profiles are active. * * @author <a href="mailto:[email protected]">Brian Fox</a> */ public class RequireActiveProfile extends AbstractNonCacheableEnforcerRule { /** Comma separated list of profiles to check. * * @see {@link #setProfiles(String)} * @see {@link #getProfiles()} */ private String profiles = null; /** If all profiles must be active. If false, only one must be active * * @see {@link #setAll(boolean)} * @see {@link #isAll()} */ private boolean all = true; public final String getProfiles() { return profiles; } public final void setProfiles( String profiles ) { this.profiles = profiles; } public final boolean isAll() { return all; } public final void setAll( boolean all ) { this.all = all; } @Override
// Path: enforcer-api/src/main/java/org/apache/maven/enforcer/rule/api/EnforcerRuleHelper.java // public interface EnforcerRuleHelper // extends ExpressionEvaluator // { // // /** // * Gets the log. // * // * @return the log // */ // @Nonnull // Log getLog (); // // /** // * Gets the component. // * // * @param clazz the clazz // * // * @return the component // * // * @throws ComponentLookupException the component lookup exception // */ // @Nonnull // <T> T getComponent ( Class<T> clazz ) // throws ComponentLookupException; // // /** // * Gets the component. // * // * @param componentKey the component key // * // * @return the component // * // * @throws ComponentLookupException the component lookup exception // */ // @Nonnull // Object getComponent ( String componentKey ) // throws ComponentLookupException; // // /** // * Gets the component. // * // * @param role the role // * @param roleHint the role hint // * // * @return the component // * // * @throws ComponentLookupException the component lookup exception // */ // Object getComponent ( String role, String roleHint ) // throws ComponentLookupException; // // /** // * Gets the component. // * // * @param clazz the clazz // * @param roleHint the role hint // * // * @return the component // * // * @throws ComponentLookupException the component lookup exception // */ // <T> T getComponent ( Class<T> clazz, String roleHint ) // throws ComponentLookupException; // // /** // * Gets the component map. // * // * @param role the role // * // * @return the component map // * // * @throws ComponentLookupException the component lookup exception // */ // Map<String, ?> getComponentMap ( String role ) // throws ComponentLookupException; // // /** // * Gets the component list. // * // * @param role the role // * // * @return the component list // * // * @throws ComponentLookupException the component lookup exception // */ // List<?> getComponentList ( String role ) // throws ComponentLookupException; // // /** // * Gets the container. // * // * @return the container // */ // PlexusContainer getContainer(); // } // Path: enforcer-rules/src/main/java/org/apache/maven/plugins/enforcer/RequireActiveProfile.java import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.maven.enforcer.rule.api.EnforcerRuleException; import org.apache.maven.enforcer.rule.api.EnforcerRuleHelper; import org.apache.maven.project.MavenProject; import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluationException; import org.codehaus.plexus.util.StringUtils; package org.apache.maven.plugins.enforcer; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /** * This rule checks that some profiles are active. * * @author <a href="mailto:[email protected]">Brian Fox</a> */ public class RequireActiveProfile extends AbstractNonCacheableEnforcerRule { /** Comma separated list of profiles to check. * * @see {@link #setProfiles(String)} * @see {@link #getProfiles()} */ private String profiles = null; /** If all profiles must be active. If false, only one must be active * * @see {@link #setAll(boolean)} * @see {@link #isAll()} */ private boolean all = true; public final String getProfiles() { return profiles; } public final void setProfiles( String profiles ) { this.profiles = profiles; } public final boolean isAll() { return all; } public final void setAll( boolean all ) { this.all = all; } @Override
public void execute( EnforcerRuleHelper theHelper )
apache/maven-enforcer
enforcer-rules/src/test/java/org/apache/maven/plugins/enforcer/TestRequireReleaseDeps.java
// Path: enforcer-api/src/main/java/org/apache/maven/enforcer/rule/api/EnforcerRuleHelper.java // public interface EnforcerRuleHelper // extends ExpressionEvaluator // { // // /** // * Gets the log. // * // * @return the log // */ // @Nonnull // Log getLog (); // // /** // * Gets the component. // * // * @param clazz the clazz // * // * @return the component // * // * @throws ComponentLookupException the component lookup exception // */ // @Nonnull // <T> T getComponent ( Class<T> clazz ) // throws ComponentLookupException; // // /** // * Gets the component. // * // * @param componentKey the component key // * // * @return the component // * // * @throws ComponentLookupException the component lookup exception // */ // @Nonnull // Object getComponent ( String componentKey ) // throws ComponentLookupException; // // /** // * Gets the component. // * // * @param role the role // * @param roleHint the role hint // * // * @return the component // * // * @throws ComponentLookupException the component lookup exception // */ // Object getComponent ( String role, String roleHint ) // throws ComponentLookupException; // // /** // * Gets the component. // * // * @param clazz the clazz // * @param roleHint the role hint // * // * @return the component // * // * @throws ComponentLookupException the component lookup exception // */ // <T> T getComponent ( Class<T> clazz, String roleHint ) // throws ComponentLookupException; // // /** // * Gets the component map. // * // * @param role the role // * // * @return the component map // * // * @throws ComponentLookupException the component lookup exception // */ // Map<String, ?> getComponentMap ( String role ) // throws ComponentLookupException; // // /** // * Gets the component list. // * // * @param role the role // * // * @return the component list // * // * @throws ComponentLookupException the component lookup exception // */ // List<?> getComponentList ( String role ) // throws ComponentLookupException; // // /** // * Gets the container. // * // * @return the container // */ // PlexusContainer getContainer(); // } // // Path: enforcer-rules/src/test/java/org/apache/maven/plugins/enforcer/utils/EnforcerRuleUtilsHelper.java // public class EnforcerRuleUtilsHelper // { // // /** // * Simpler wrapper to execute and deal with the expected result. // * // * @param rule the rule // * @param helper the helper // * @param shouldFail the should fail // */ // public static void execute( EnforcerRule rule, EnforcerRuleHelper helper, boolean shouldFail ) // { // try // { // rule.execute( helper ); // if ( shouldFail ) // { // fail( "Exception expected." ); // } // } // catch ( EnforcerRuleException e ) // { // if ( !shouldFail ) // { // fail( "No Exception expected:" + e.getMessage() ); // } // helper.getLog().debug( e.getMessage() ); // } // } // }
import java.util.Collections; import java.util.Set; import org.apache.maven.artifact.Artifact; import org.apache.maven.enforcer.rule.api.EnforcerRuleHelper; import org.apache.maven.plugin.testing.ArtifactStubFactory; import org.apache.maven.plugins.enforcer.utils.EnforcerRuleUtilsHelper; import org.apache.maven.project.MavenProject; import org.apache.maven.project.ProjectBuildingRequest; import org.junit.jupiter.api.Test;
package org.apache.maven.plugins.enforcer; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /** * The Class TestNoSnapshots. * * @author <a href="mailto:[email protected]">Brian Fox</a> */ public class TestRequireReleaseDeps { /** * Test rule. * * @throws Exception if any occurs */ @Test public void testRule() throws Exception { ArtifactStubFactory factory = new ArtifactStubFactory(); MockProject project = new MockProject();
// Path: enforcer-api/src/main/java/org/apache/maven/enforcer/rule/api/EnforcerRuleHelper.java // public interface EnforcerRuleHelper // extends ExpressionEvaluator // { // // /** // * Gets the log. // * // * @return the log // */ // @Nonnull // Log getLog (); // // /** // * Gets the component. // * // * @param clazz the clazz // * // * @return the component // * // * @throws ComponentLookupException the component lookup exception // */ // @Nonnull // <T> T getComponent ( Class<T> clazz ) // throws ComponentLookupException; // // /** // * Gets the component. // * // * @param componentKey the component key // * // * @return the component // * // * @throws ComponentLookupException the component lookup exception // */ // @Nonnull // Object getComponent ( String componentKey ) // throws ComponentLookupException; // // /** // * Gets the component. // * // * @param role the role // * @param roleHint the role hint // * // * @return the component // * // * @throws ComponentLookupException the component lookup exception // */ // Object getComponent ( String role, String roleHint ) // throws ComponentLookupException; // // /** // * Gets the component. // * // * @param clazz the clazz // * @param roleHint the role hint // * // * @return the component // * // * @throws ComponentLookupException the component lookup exception // */ // <T> T getComponent ( Class<T> clazz, String roleHint ) // throws ComponentLookupException; // // /** // * Gets the component map. // * // * @param role the role // * // * @return the component map // * // * @throws ComponentLookupException the component lookup exception // */ // Map<String, ?> getComponentMap ( String role ) // throws ComponentLookupException; // // /** // * Gets the component list. // * // * @param role the role // * // * @return the component list // * // * @throws ComponentLookupException the component lookup exception // */ // List<?> getComponentList ( String role ) // throws ComponentLookupException; // // /** // * Gets the container. // * // * @return the container // */ // PlexusContainer getContainer(); // } // // Path: enforcer-rules/src/test/java/org/apache/maven/plugins/enforcer/utils/EnforcerRuleUtilsHelper.java // public class EnforcerRuleUtilsHelper // { // // /** // * Simpler wrapper to execute and deal with the expected result. // * // * @param rule the rule // * @param helper the helper // * @param shouldFail the should fail // */ // public static void execute( EnforcerRule rule, EnforcerRuleHelper helper, boolean shouldFail ) // { // try // { // rule.execute( helper ); // if ( shouldFail ) // { // fail( "Exception expected." ); // } // } // catch ( EnforcerRuleException e ) // { // if ( !shouldFail ) // { // fail( "No Exception expected:" + e.getMessage() ); // } // helper.getLog().debug( e.getMessage() ); // } // } // } // Path: enforcer-rules/src/test/java/org/apache/maven/plugins/enforcer/TestRequireReleaseDeps.java import java.util.Collections; import java.util.Set; import org.apache.maven.artifact.Artifact; import org.apache.maven.enforcer.rule.api.EnforcerRuleHelper; import org.apache.maven.plugin.testing.ArtifactStubFactory; import org.apache.maven.plugins.enforcer.utils.EnforcerRuleUtilsHelper; import org.apache.maven.project.MavenProject; import org.apache.maven.project.ProjectBuildingRequest; import org.junit.jupiter.api.Test; package org.apache.maven.plugins.enforcer; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /** * The Class TestNoSnapshots. * * @author <a href="mailto:[email protected]">Brian Fox</a> */ public class TestRequireReleaseDeps { /** * Test rule. * * @throws Exception if any occurs */ @Test public void testRule() throws Exception { ArtifactStubFactory factory = new ArtifactStubFactory(); MockProject project = new MockProject();
EnforcerRuleHelper helper = EnforcerTestUtils.getHelper( project );
apache/maven-enforcer
enforcer-rules/src/test/java/org/apache/maven/plugins/enforcer/TestRequireReleaseDeps.java
// Path: enforcer-api/src/main/java/org/apache/maven/enforcer/rule/api/EnforcerRuleHelper.java // public interface EnforcerRuleHelper // extends ExpressionEvaluator // { // // /** // * Gets the log. // * // * @return the log // */ // @Nonnull // Log getLog (); // // /** // * Gets the component. // * // * @param clazz the clazz // * // * @return the component // * // * @throws ComponentLookupException the component lookup exception // */ // @Nonnull // <T> T getComponent ( Class<T> clazz ) // throws ComponentLookupException; // // /** // * Gets the component. // * // * @param componentKey the component key // * // * @return the component // * // * @throws ComponentLookupException the component lookup exception // */ // @Nonnull // Object getComponent ( String componentKey ) // throws ComponentLookupException; // // /** // * Gets the component. // * // * @param role the role // * @param roleHint the role hint // * // * @return the component // * // * @throws ComponentLookupException the component lookup exception // */ // Object getComponent ( String role, String roleHint ) // throws ComponentLookupException; // // /** // * Gets the component. // * // * @param clazz the clazz // * @param roleHint the role hint // * // * @return the component // * // * @throws ComponentLookupException the component lookup exception // */ // <T> T getComponent ( Class<T> clazz, String roleHint ) // throws ComponentLookupException; // // /** // * Gets the component map. // * // * @param role the role // * // * @return the component map // * // * @throws ComponentLookupException the component lookup exception // */ // Map<String, ?> getComponentMap ( String role ) // throws ComponentLookupException; // // /** // * Gets the component list. // * // * @param role the role // * // * @return the component list // * // * @throws ComponentLookupException the component lookup exception // */ // List<?> getComponentList ( String role ) // throws ComponentLookupException; // // /** // * Gets the container. // * // * @return the container // */ // PlexusContainer getContainer(); // } // // Path: enforcer-rules/src/test/java/org/apache/maven/plugins/enforcer/utils/EnforcerRuleUtilsHelper.java // public class EnforcerRuleUtilsHelper // { // // /** // * Simpler wrapper to execute and deal with the expected result. // * // * @param rule the rule // * @param helper the helper // * @param shouldFail the should fail // */ // public static void execute( EnforcerRule rule, EnforcerRuleHelper helper, boolean shouldFail ) // { // try // { // rule.execute( helper ); // if ( shouldFail ) // { // fail( "Exception expected." ); // } // } // catch ( EnforcerRuleException e ) // { // if ( !shouldFail ) // { // fail( "No Exception expected:" + e.getMessage() ); // } // helper.getLog().debug( e.getMessage() ); // } // } // }
import java.util.Collections; import java.util.Set; import org.apache.maven.artifact.Artifact; import org.apache.maven.enforcer.rule.api.EnforcerRuleHelper; import org.apache.maven.plugin.testing.ArtifactStubFactory; import org.apache.maven.plugins.enforcer.utils.EnforcerRuleUtilsHelper; import org.apache.maven.project.MavenProject; import org.apache.maven.project.ProjectBuildingRequest; import org.junit.jupiter.api.Test;
package org.apache.maven.plugins.enforcer; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /** * The Class TestNoSnapshots. * * @author <a href="mailto:[email protected]">Brian Fox</a> */ public class TestRequireReleaseDeps { /** * Test rule. * * @throws Exception if any occurs */ @Test public void testRule() throws Exception { ArtifactStubFactory factory = new ArtifactStubFactory(); MockProject project = new MockProject(); EnforcerRuleHelper helper = EnforcerTestUtils.getHelper( project ); project.setArtifacts( factory.getMixedArtifacts() ); project.setDependencyArtifacts( factory.getScopedArtifacts() ); RequireReleaseDeps rule = newRequireReleaseDeps(); rule.setSearchTransitive( false );
// Path: enforcer-api/src/main/java/org/apache/maven/enforcer/rule/api/EnforcerRuleHelper.java // public interface EnforcerRuleHelper // extends ExpressionEvaluator // { // // /** // * Gets the log. // * // * @return the log // */ // @Nonnull // Log getLog (); // // /** // * Gets the component. // * // * @param clazz the clazz // * // * @return the component // * // * @throws ComponentLookupException the component lookup exception // */ // @Nonnull // <T> T getComponent ( Class<T> clazz ) // throws ComponentLookupException; // // /** // * Gets the component. // * // * @param componentKey the component key // * // * @return the component // * // * @throws ComponentLookupException the component lookup exception // */ // @Nonnull // Object getComponent ( String componentKey ) // throws ComponentLookupException; // // /** // * Gets the component. // * // * @param role the role // * @param roleHint the role hint // * // * @return the component // * // * @throws ComponentLookupException the component lookup exception // */ // Object getComponent ( String role, String roleHint ) // throws ComponentLookupException; // // /** // * Gets the component. // * // * @param clazz the clazz // * @param roleHint the role hint // * // * @return the component // * // * @throws ComponentLookupException the component lookup exception // */ // <T> T getComponent ( Class<T> clazz, String roleHint ) // throws ComponentLookupException; // // /** // * Gets the component map. // * // * @param role the role // * // * @return the component map // * // * @throws ComponentLookupException the component lookup exception // */ // Map<String, ?> getComponentMap ( String role ) // throws ComponentLookupException; // // /** // * Gets the component list. // * // * @param role the role // * // * @return the component list // * // * @throws ComponentLookupException the component lookup exception // */ // List<?> getComponentList ( String role ) // throws ComponentLookupException; // // /** // * Gets the container. // * // * @return the container // */ // PlexusContainer getContainer(); // } // // Path: enforcer-rules/src/test/java/org/apache/maven/plugins/enforcer/utils/EnforcerRuleUtilsHelper.java // public class EnforcerRuleUtilsHelper // { // // /** // * Simpler wrapper to execute and deal with the expected result. // * // * @param rule the rule // * @param helper the helper // * @param shouldFail the should fail // */ // public static void execute( EnforcerRule rule, EnforcerRuleHelper helper, boolean shouldFail ) // { // try // { // rule.execute( helper ); // if ( shouldFail ) // { // fail( "Exception expected." ); // } // } // catch ( EnforcerRuleException e ) // { // if ( !shouldFail ) // { // fail( "No Exception expected:" + e.getMessage() ); // } // helper.getLog().debug( e.getMessage() ); // } // } // } // Path: enforcer-rules/src/test/java/org/apache/maven/plugins/enforcer/TestRequireReleaseDeps.java import java.util.Collections; import java.util.Set; import org.apache.maven.artifact.Artifact; import org.apache.maven.enforcer.rule.api.EnforcerRuleHelper; import org.apache.maven.plugin.testing.ArtifactStubFactory; import org.apache.maven.plugins.enforcer.utils.EnforcerRuleUtilsHelper; import org.apache.maven.project.MavenProject; import org.apache.maven.project.ProjectBuildingRequest; import org.junit.jupiter.api.Test; package org.apache.maven.plugins.enforcer; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /** * The Class TestNoSnapshots. * * @author <a href="mailto:[email protected]">Brian Fox</a> */ public class TestRequireReleaseDeps { /** * Test rule. * * @throws Exception if any occurs */ @Test public void testRule() throws Exception { ArtifactStubFactory factory = new ArtifactStubFactory(); MockProject project = new MockProject(); EnforcerRuleHelper helper = EnforcerTestUtils.getHelper( project ); project.setArtifacts( factory.getMixedArtifacts() ); project.setDependencyArtifacts( factory.getScopedArtifacts() ); RequireReleaseDeps rule = newRequireReleaseDeps(); rule.setSearchTransitive( false );
EnforcerRuleUtilsHelper.execute( rule, helper, false );
apache/maven-enforcer
enforcer-rules/src/main/java/org/apache/maven/plugins/enforcer/BannedRepositories.java
// Path: enforcer-api/src/main/java/org/apache/maven/enforcer/rule/api/EnforcerRuleHelper.java // public interface EnforcerRuleHelper // extends ExpressionEvaluator // { // // /** // * Gets the log. // * // * @return the log // */ // @Nonnull // Log getLog (); // // /** // * Gets the component. // * // * @param clazz the clazz // * // * @return the component // * // * @throws ComponentLookupException the component lookup exception // */ // @Nonnull // <T> T getComponent ( Class<T> clazz ) // throws ComponentLookupException; // // /** // * Gets the component. // * // * @param componentKey the component key // * // * @return the component // * // * @throws ComponentLookupException the component lookup exception // */ // @Nonnull // Object getComponent ( String componentKey ) // throws ComponentLookupException; // // /** // * Gets the component. // * // * @param role the role // * @param roleHint the role hint // * // * @return the component // * // * @throws ComponentLookupException the component lookup exception // */ // Object getComponent ( String role, String roleHint ) // throws ComponentLookupException; // // /** // * Gets the component. // * // * @param clazz the clazz // * @param roleHint the role hint // * // * @return the component // * // * @throws ComponentLookupException the component lookup exception // */ // <T> T getComponent ( Class<T> clazz, String roleHint ) // throws ComponentLookupException; // // /** // * Gets the component map. // * // * @param role the role // * // * @return the component map // * // * @throws ComponentLookupException the component lookup exception // */ // Map<String, ?> getComponentMap ( String role ) // throws ComponentLookupException; // // /** // * Gets the component list. // * // * @param role the role // * // * @return the component list // * // * @throws ComponentLookupException the component lookup exception // */ // List<?> getComponentList ( String role ) // throws ComponentLookupException; // // /** // * Gets the container. // * // * @return the container // */ // PlexusContainer getContainer(); // }
import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.enforcer.rule.api.EnforcerRuleException; import org.apache.maven.enforcer.rule.api.EnforcerRuleHelper; import org.apache.maven.project.MavenProject; import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluationException; import org.codehaus.plexus.util.StringUtils;
package org.apache.maven.plugins.enforcer; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /** * This rule checks that this project's maven session whether have banned repositories. * * @author <a href="mailto:[email protected]">Simon Wang</a> */ public class BannedRepositories extends AbstractNonCacheableEnforcerRule { // ---------------------------------------------------------------------- // Mojo parameters // ---------------------------------------------------------------------- /** * Specify explicitly banned non-plugin repositories. This is a list of repository url patterns. Support wildcard * "*". * * @see {@link #setBannedRepositories(List)} */ private List<String> bannedRepositories = Collections.emptyList(); /** * Specify explicitly banned plugin repositories. This is a list of repository url patterns. Support wildcard "*". * * @see {@link #setBannedPluginRepositories(List)} */ private List<String> bannedPluginRepositories = Collections.emptyList(); /** * Specify explicitly allowed non-plugin repositories, then all others repositories would be banned. This is a list * of repository url patterns. Support wildcard "*". * * @see {@link #setAllowedRepositories(List)} */ private List<String> allowedRepositories = Collections.emptyList(); /** * Specify explicitly allowed plugin repositories, then all others repositories would be banned. This is a list of * repository url patterns. Support wildcard "*". * * @see {@link #setAllowedPluginRepositories(List)} */ private List<String> allowedPluginRepositories = Collections.emptyList(); // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- @Override
// Path: enforcer-api/src/main/java/org/apache/maven/enforcer/rule/api/EnforcerRuleHelper.java // public interface EnforcerRuleHelper // extends ExpressionEvaluator // { // // /** // * Gets the log. // * // * @return the log // */ // @Nonnull // Log getLog (); // // /** // * Gets the component. // * // * @param clazz the clazz // * // * @return the component // * // * @throws ComponentLookupException the component lookup exception // */ // @Nonnull // <T> T getComponent ( Class<T> clazz ) // throws ComponentLookupException; // // /** // * Gets the component. // * // * @param componentKey the component key // * // * @return the component // * // * @throws ComponentLookupException the component lookup exception // */ // @Nonnull // Object getComponent ( String componentKey ) // throws ComponentLookupException; // // /** // * Gets the component. // * // * @param role the role // * @param roleHint the role hint // * // * @return the component // * // * @throws ComponentLookupException the component lookup exception // */ // Object getComponent ( String role, String roleHint ) // throws ComponentLookupException; // // /** // * Gets the component. // * // * @param clazz the clazz // * @param roleHint the role hint // * // * @return the component // * // * @throws ComponentLookupException the component lookup exception // */ // <T> T getComponent ( Class<T> clazz, String roleHint ) // throws ComponentLookupException; // // /** // * Gets the component map. // * // * @param role the role // * // * @return the component map // * // * @throws ComponentLookupException the component lookup exception // */ // Map<String, ?> getComponentMap ( String role ) // throws ComponentLookupException; // // /** // * Gets the component list. // * // * @param role the role // * // * @return the component list // * // * @throws ComponentLookupException the component lookup exception // */ // List<?> getComponentList ( String role ) // throws ComponentLookupException; // // /** // * Gets the container. // * // * @return the container // */ // PlexusContainer getContainer(); // } // Path: enforcer-rules/src/main/java/org/apache/maven/plugins/enforcer/BannedRepositories.java import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.enforcer.rule.api.EnforcerRuleException; import org.apache.maven.enforcer.rule.api.EnforcerRuleHelper; import org.apache.maven.project.MavenProject; import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluationException; import org.codehaus.plexus.util.StringUtils; package org.apache.maven.plugins.enforcer; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /** * This rule checks that this project's maven session whether have banned repositories. * * @author <a href="mailto:[email protected]">Simon Wang</a> */ public class BannedRepositories extends AbstractNonCacheableEnforcerRule { // ---------------------------------------------------------------------- // Mojo parameters // ---------------------------------------------------------------------- /** * Specify explicitly banned non-plugin repositories. This is a list of repository url patterns. Support wildcard * "*". * * @see {@link #setBannedRepositories(List)} */ private List<String> bannedRepositories = Collections.emptyList(); /** * Specify explicitly banned plugin repositories. This is a list of repository url patterns. Support wildcard "*". * * @see {@link #setBannedPluginRepositories(List)} */ private List<String> bannedPluginRepositories = Collections.emptyList(); /** * Specify explicitly allowed non-plugin repositories, then all others repositories would be banned. This is a list * of repository url patterns. Support wildcard "*". * * @see {@link #setAllowedRepositories(List)} */ private List<String> allowedRepositories = Collections.emptyList(); /** * Specify explicitly allowed plugin repositories, then all others repositories would be banned. This is a list of * repository url patterns. Support wildcard "*". * * @see {@link #setAllowedPluginRepositories(List)} */ private List<String> allowedPluginRepositories = Collections.emptyList(); // ---------------------------------------------------------------------- // Public methods // ---------------------------------------------------------------------- @Override
public void execute( EnforcerRuleHelper helper )
apache/maven-enforcer
enforcer-rules/src/main/java/org/apache/maven/plugins/enforcer/AbstractPropertyEnforcerRule.java
// Path: enforcer-api/src/main/java/org/apache/maven/enforcer/rule/api/EnforcerRuleHelper.java // public interface EnforcerRuleHelper // extends ExpressionEvaluator // { // // /** // * Gets the log. // * // * @return the log // */ // @Nonnull // Log getLog (); // // /** // * Gets the component. // * // * @param clazz the clazz // * // * @return the component // * // * @throws ComponentLookupException the component lookup exception // */ // @Nonnull // <T> T getComponent ( Class<T> clazz ) // throws ComponentLookupException; // // /** // * Gets the component. // * // * @param componentKey the component key // * // * @return the component // * // * @throws ComponentLookupException the component lookup exception // */ // @Nonnull // Object getComponent ( String componentKey ) // throws ComponentLookupException; // // /** // * Gets the component. // * // * @param role the role // * @param roleHint the role hint // * // * @return the component // * // * @throws ComponentLookupException the component lookup exception // */ // Object getComponent ( String role, String roleHint ) // throws ComponentLookupException; // // /** // * Gets the component. // * // * @param clazz the clazz // * @param roleHint the role hint // * // * @return the component // * // * @throws ComponentLookupException the component lookup exception // */ // <T> T getComponent ( Class<T> clazz, String roleHint ) // throws ComponentLookupException; // // /** // * Gets the component map. // * // * @param role the role // * // * @return the component map // * // * @throws ComponentLookupException the component lookup exception // */ // Map<String, ?> getComponentMap ( String role ) // throws ComponentLookupException; // // /** // * Gets the component list. // * // * @param role the role // * // * @return the component list // * // * @throws ComponentLookupException the component lookup exception // */ // List<?> getComponentList ( String role ) // throws ComponentLookupException; // // /** // * Gets the container. // * // * @return the container // */ // PlexusContainer getContainer(); // }
import org.apache.maven.enforcer.rule.api.EnforcerRuleException; import org.apache.maven.enforcer.rule.api.EnforcerRuleHelper;
package org.apache.maven.plugins.enforcer; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /** * Abstract enforcer rule that give a foundation to validate properties from multiple sources. * * @author Paul Gier * @author <a href='mailto:marvin[at]marvinformatics[dot]com'>Marvin Froeder</a> */ public abstract class AbstractPropertyEnforcerRule extends AbstractNonCacheableEnforcerRule { /** * Match the property value to a given regular expression. Defaults to <code>null</code> (any value is ok). * * @see {@link #setRegex(String)} * @see {@link #getRegex()} */ private String regex = null; /** * Specify a warning message if the regular expression is not matched. * * @see {@link #setRegexMessage(String)} * @see {@link #getRegexMessage()} */ private String regexMessage = null; public AbstractPropertyEnforcerRule() { super(); } /** * Set the property value to a given regular expression. Defaults to <code>null</code> (any value is ok). * * @param regex The regular expression */ public final void setRegex( String regex ) { this.regex = regex; } /** * Get the property value to a given regular expression. Defaults to <code>null</code> (any value is ok). * * @return the regular expression */ public final String getRegex() { return regex; } /** * Set a warning message if the regular expression is not matched. * * @param regexMessage the regex message */ public final void setRegexMessage( String regexMessage ) { this.regexMessage = regexMessage; } /** * Get a warning message if the regular expression is not matched. * * @return the regex message */ public final String getRegexMessage() { return regexMessage; } @Override
// Path: enforcer-api/src/main/java/org/apache/maven/enforcer/rule/api/EnforcerRuleHelper.java // public interface EnforcerRuleHelper // extends ExpressionEvaluator // { // // /** // * Gets the log. // * // * @return the log // */ // @Nonnull // Log getLog (); // // /** // * Gets the component. // * // * @param clazz the clazz // * // * @return the component // * // * @throws ComponentLookupException the component lookup exception // */ // @Nonnull // <T> T getComponent ( Class<T> clazz ) // throws ComponentLookupException; // // /** // * Gets the component. // * // * @param componentKey the component key // * // * @return the component // * // * @throws ComponentLookupException the component lookup exception // */ // @Nonnull // Object getComponent ( String componentKey ) // throws ComponentLookupException; // // /** // * Gets the component. // * // * @param role the role // * @param roleHint the role hint // * // * @return the component // * // * @throws ComponentLookupException the component lookup exception // */ // Object getComponent ( String role, String roleHint ) // throws ComponentLookupException; // // /** // * Gets the component. // * // * @param clazz the clazz // * @param roleHint the role hint // * // * @return the component // * // * @throws ComponentLookupException the component lookup exception // */ // <T> T getComponent ( Class<T> clazz, String roleHint ) // throws ComponentLookupException; // // /** // * Gets the component map. // * // * @param role the role // * // * @return the component map // * // * @throws ComponentLookupException the component lookup exception // */ // Map<String, ?> getComponentMap ( String role ) // throws ComponentLookupException; // // /** // * Gets the component list. // * // * @param role the role // * // * @return the component list // * // * @throws ComponentLookupException the component lookup exception // */ // List<?> getComponentList ( String role ) // throws ComponentLookupException; // // /** // * Gets the container. // * // * @return the container // */ // PlexusContainer getContainer(); // } // Path: enforcer-rules/src/main/java/org/apache/maven/plugins/enforcer/AbstractPropertyEnforcerRule.java import org.apache.maven.enforcer.rule.api.EnforcerRuleException; import org.apache.maven.enforcer.rule.api.EnforcerRuleHelper; package org.apache.maven.plugins.enforcer; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /** * Abstract enforcer rule that give a foundation to validate properties from multiple sources. * * @author Paul Gier * @author <a href='mailto:marvin[at]marvinformatics[dot]com'>Marvin Froeder</a> */ public abstract class AbstractPropertyEnforcerRule extends AbstractNonCacheableEnforcerRule { /** * Match the property value to a given regular expression. Defaults to <code>null</code> (any value is ok). * * @see {@link #setRegex(String)} * @see {@link #getRegex()} */ private String regex = null; /** * Specify a warning message if the regular expression is not matched. * * @see {@link #setRegexMessage(String)} * @see {@link #getRegexMessage()} */ private String regexMessage = null; public AbstractPropertyEnforcerRule() { super(); } /** * Set the property value to a given regular expression. Defaults to <code>null</code> (any value is ok). * * @param regex The regular expression */ public final void setRegex( String regex ) { this.regex = regex; } /** * Get the property value to a given regular expression. Defaults to <code>null</code> (any value is ok). * * @return the regular expression */ public final String getRegex() { return regex; } /** * Set a warning message if the regular expression is not matched. * * @param regexMessage the regex message */ public final void setRegexMessage( String regexMessage ) { this.regexMessage = regexMessage; } /** * Get a warning message if the regular expression is not matched. * * @return the regex message */ public final String getRegexMessage() { return regexMessage; } @Override
public void execute( EnforcerRuleHelper helper )