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
Omegapoint/facepalm
src/main/java/se/omegapoint/facepalm/application/ImageService.java
// Path: src/main/java/se/omegapoint/facepalm/application/transfer/NewImageComment.java // public class NewImageComment { // public final Long imageId; // public final String author; // public final String text; // // public NewImageComment(final Long imageId, final String author, final String text) { // this.imageId = notNull(imageId); // this.author = notBlank(author); // this.text = notBlank(text); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/Image.java // public class Image { // public final byte[] data; // // public Image(final byte[] data) { // this.data = notNull(data); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/ImageComment.java // public class ImageComment { // // public final Long imageId; // public final String author; // public final String text; // // public ImageComment(final Long imageId, final String author, final String text) { // this.imageId = imageId; // this.author = author; // this.text = text; // } // // @Override // public String toString() { // return "ImageComment{" + // "imageId=" + imageId + // ", author='" + author + '\'' + // ", text='" + text + '\'' + // '}'; // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/ImagePost.java // public class ImagePost { // public final Long id; // public final Title title; // public final NumberOfPoints numPoints; // public final NumberOfComments numComments; // // public ImagePost(final Long id, final Title title, final NumberOfPoints points, final NumberOfComments numComments) { // this.id = notNull(id); // this.title = notNull(title); // this.numPoints = notNull(points); // this.numComments = notNull(numComments); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/Title.java // public class Title { // private static final int MAN_LENGTH = 100; // // public final String value; // // public Title(final String value) { // this.value = notBlank(value); // isTrue(this.value.length() < MAN_LENGTH, "Title can be maximum 100 characters"); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/repository/CommentRepository.java // public interface CommentRepository { // List<ImageComment> findByImageId(final Long id); // // void addComment(Long imageId, String author, String text); // } // // Path: src/main/java/se/omegapoint/facepalm/domain/repository/ImageRepository.java // public interface ImageRepository { // List<ImagePost> findAll(); // // Optional<ImagePost> findById(String id); // // void addImagePost(Title title, byte[] data); // // Image findImageByPostId(Long id); // }
import static org.apache.commons.lang3.Validate.notBlank; import static org.apache.commons.lang3.Validate.notNull; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import se.omegapoint.facepalm.application.transfer.NewImageComment; import se.omegapoint.facepalm.domain.Image; import se.omegapoint.facepalm.domain.ImageComment; import se.omegapoint.facepalm.domain.ImagePost; import se.omegapoint.facepalm.domain.Title; import se.omegapoint.facepalm.domain.repository.CommentRepository; import se.omegapoint.facepalm.domain.repository.ImageRepository; import java.util.List; import java.util.Optional; import static java.util.stream.Collectors.toList;
/* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.application; @Service public class ImageService { @Autowired private ImageRepository imageRepository; @Autowired private CommentRepository commentRepository; public List<ImagePost> getTopImages() { return imageRepository.findAll(); } public Optional<ImagePost> getImagePost(final String id) { notBlank(id); return imageRepository.findById(id); } public List<ImageComment> getCommentsForImage(final Long id) { notNull(id); return commentRepository.findByImageId(id).stream().collect(toList()); }
// Path: src/main/java/se/omegapoint/facepalm/application/transfer/NewImageComment.java // public class NewImageComment { // public final Long imageId; // public final String author; // public final String text; // // public NewImageComment(final Long imageId, final String author, final String text) { // this.imageId = notNull(imageId); // this.author = notBlank(author); // this.text = notBlank(text); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/Image.java // public class Image { // public final byte[] data; // // public Image(final byte[] data) { // this.data = notNull(data); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/ImageComment.java // public class ImageComment { // // public final Long imageId; // public final String author; // public final String text; // // public ImageComment(final Long imageId, final String author, final String text) { // this.imageId = imageId; // this.author = author; // this.text = text; // } // // @Override // public String toString() { // return "ImageComment{" + // "imageId=" + imageId + // ", author='" + author + '\'' + // ", text='" + text + '\'' + // '}'; // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/ImagePost.java // public class ImagePost { // public final Long id; // public final Title title; // public final NumberOfPoints numPoints; // public final NumberOfComments numComments; // // public ImagePost(final Long id, final Title title, final NumberOfPoints points, final NumberOfComments numComments) { // this.id = notNull(id); // this.title = notNull(title); // this.numPoints = notNull(points); // this.numComments = notNull(numComments); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/Title.java // public class Title { // private static final int MAN_LENGTH = 100; // // public final String value; // // public Title(final String value) { // this.value = notBlank(value); // isTrue(this.value.length() < MAN_LENGTH, "Title can be maximum 100 characters"); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/repository/CommentRepository.java // public interface CommentRepository { // List<ImageComment> findByImageId(final Long id); // // void addComment(Long imageId, String author, String text); // } // // Path: src/main/java/se/omegapoint/facepalm/domain/repository/ImageRepository.java // public interface ImageRepository { // List<ImagePost> findAll(); // // Optional<ImagePost> findById(String id); // // void addImagePost(Title title, byte[] data); // // Image findImageByPostId(Long id); // } // Path: src/main/java/se/omegapoint/facepalm/application/ImageService.java import static org.apache.commons.lang3.Validate.notBlank; import static org.apache.commons.lang3.Validate.notNull; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import se.omegapoint.facepalm.application.transfer.NewImageComment; import se.omegapoint.facepalm.domain.Image; import se.omegapoint.facepalm.domain.ImageComment; import se.omegapoint.facepalm.domain.ImagePost; import se.omegapoint.facepalm.domain.Title; import se.omegapoint.facepalm.domain.repository.CommentRepository; import se.omegapoint.facepalm.domain.repository.ImageRepository; import java.util.List; import java.util.Optional; import static java.util.stream.Collectors.toList; /* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.application; @Service public class ImageService { @Autowired private ImageRepository imageRepository; @Autowired private CommentRepository commentRepository; public List<ImagePost> getTopImages() { return imageRepository.findAll(); } public Optional<ImagePost> getImagePost(final String id) { notBlank(id); return imageRepository.findById(id); } public List<ImageComment> getCommentsForImage(final Long id) { notNull(id); return commentRepository.findByImageId(id).stream().collect(toList()); }
public void addComment(final NewImageComment newImageComment) {
Omegapoint/facepalm
src/main/java/se/omegapoint/facepalm/application/ImageService.java
// Path: src/main/java/se/omegapoint/facepalm/application/transfer/NewImageComment.java // public class NewImageComment { // public final Long imageId; // public final String author; // public final String text; // // public NewImageComment(final Long imageId, final String author, final String text) { // this.imageId = notNull(imageId); // this.author = notBlank(author); // this.text = notBlank(text); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/Image.java // public class Image { // public final byte[] data; // // public Image(final byte[] data) { // this.data = notNull(data); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/ImageComment.java // public class ImageComment { // // public final Long imageId; // public final String author; // public final String text; // // public ImageComment(final Long imageId, final String author, final String text) { // this.imageId = imageId; // this.author = author; // this.text = text; // } // // @Override // public String toString() { // return "ImageComment{" + // "imageId=" + imageId + // ", author='" + author + '\'' + // ", text='" + text + '\'' + // '}'; // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/ImagePost.java // public class ImagePost { // public final Long id; // public final Title title; // public final NumberOfPoints numPoints; // public final NumberOfComments numComments; // // public ImagePost(final Long id, final Title title, final NumberOfPoints points, final NumberOfComments numComments) { // this.id = notNull(id); // this.title = notNull(title); // this.numPoints = notNull(points); // this.numComments = notNull(numComments); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/Title.java // public class Title { // private static final int MAN_LENGTH = 100; // // public final String value; // // public Title(final String value) { // this.value = notBlank(value); // isTrue(this.value.length() < MAN_LENGTH, "Title can be maximum 100 characters"); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/repository/CommentRepository.java // public interface CommentRepository { // List<ImageComment> findByImageId(final Long id); // // void addComment(Long imageId, String author, String text); // } // // Path: src/main/java/se/omegapoint/facepalm/domain/repository/ImageRepository.java // public interface ImageRepository { // List<ImagePost> findAll(); // // Optional<ImagePost> findById(String id); // // void addImagePost(Title title, byte[] data); // // Image findImageByPostId(Long id); // }
import static org.apache.commons.lang3.Validate.notBlank; import static org.apache.commons.lang3.Validate.notNull; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import se.omegapoint.facepalm.application.transfer.NewImageComment; import se.omegapoint.facepalm.domain.Image; import se.omegapoint.facepalm.domain.ImageComment; import se.omegapoint.facepalm.domain.ImagePost; import se.omegapoint.facepalm.domain.Title; import se.omegapoint.facepalm.domain.repository.CommentRepository; import se.omegapoint.facepalm.domain.repository.ImageRepository; import java.util.List; import java.util.Optional; import static java.util.stream.Collectors.toList;
/* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.application; @Service public class ImageService { @Autowired private ImageRepository imageRepository; @Autowired private CommentRepository commentRepository; public List<ImagePost> getTopImages() { return imageRepository.findAll(); } public Optional<ImagePost> getImagePost(final String id) { notBlank(id); return imageRepository.findById(id); } public List<ImageComment> getCommentsForImage(final Long id) { notNull(id); return commentRepository.findByImageId(id).stream().collect(toList()); } public void addComment(final NewImageComment newImageComment) { notNull(newImageComment); commentRepository.addComment(newImageComment.imageId, newImageComment.author, newImageComment.text); }
// Path: src/main/java/se/omegapoint/facepalm/application/transfer/NewImageComment.java // public class NewImageComment { // public final Long imageId; // public final String author; // public final String text; // // public NewImageComment(final Long imageId, final String author, final String text) { // this.imageId = notNull(imageId); // this.author = notBlank(author); // this.text = notBlank(text); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/Image.java // public class Image { // public final byte[] data; // // public Image(final byte[] data) { // this.data = notNull(data); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/ImageComment.java // public class ImageComment { // // public final Long imageId; // public final String author; // public final String text; // // public ImageComment(final Long imageId, final String author, final String text) { // this.imageId = imageId; // this.author = author; // this.text = text; // } // // @Override // public String toString() { // return "ImageComment{" + // "imageId=" + imageId + // ", author='" + author + '\'' + // ", text='" + text + '\'' + // '}'; // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/ImagePost.java // public class ImagePost { // public final Long id; // public final Title title; // public final NumberOfPoints numPoints; // public final NumberOfComments numComments; // // public ImagePost(final Long id, final Title title, final NumberOfPoints points, final NumberOfComments numComments) { // this.id = notNull(id); // this.title = notNull(title); // this.numPoints = notNull(points); // this.numComments = notNull(numComments); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/Title.java // public class Title { // private static final int MAN_LENGTH = 100; // // public final String value; // // public Title(final String value) { // this.value = notBlank(value); // isTrue(this.value.length() < MAN_LENGTH, "Title can be maximum 100 characters"); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/repository/CommentRepository.java // public interface CommentRepository { // List<ImageComment> findByImageId(final Long id); // // void addComment(Long imageId, String author, String text); // } // // Path: src/main/java/se/omegapoint/facepalm/domain/repository/ImageRepository.java // public interface ImageRepository { // List<ImagePost> findAll(); // // Optional<ImagePost> findById(String id); // // void addImagePost(Title title, byte[] data); // // Image findImageByPostId(Long id); // } // Path: src/main/java/se/omegapoint/facepalm/application/ImageService.java import static org.apache.commons.lang3.Validate.notBlank; import static org.apache.commons.lang3.Validate.notNull; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import se.omegapoint.facepalm.application.transfer.NewImageComment; import se.omegapoint.facepalm.domain.Image; import se.omegapoint.facepalm.domain.ImageComment; import se.omegapoint.facepalm.domain.ImagePost; import se.omegapoint.facepalm.domain.Title; import se.omegapoint.facepalm.domain.repository.CommentRepository; import se.omegapoint.facepalm.domain.repository.ImageRepository; import java.util.List; import java.util.Optional; import static java.util.stream.Collectors.toList; /* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.application; @Service public class ImageService { @Autowired private ImageRepository imageRepository; @Autowired private CommentRepository commentRepository; public List<ImagePost> getTopImages() { return imageRepository.findAll(); } public Optional<ImagePost> getImagePost(final String id) { notBlank(id); return imageRepository.findById(id); } public List<ImageComment> getCommentsForImage(final Long id) { notNull(id); return commentRepository.findByImageId(id).stream().collect(toList()); } public void addComment(final NewImageComment newImageComment) { notNull(newImageComment); commentRepository.addComment(newImageComment.imageId, newImageComment.author, newImageComment.text); }
public void addImagePost(final Title title, final byte[] data) {
Omegapoint/facepalm
src/main/java/se/omegapoint/facepalm/application/ImageService.java
// Path: src/main/java/se/omegapoint/facepalm/application/transfer/NewImageComment.java // public class NewImageComment { // public final Long imageId; // public final String author; // public final String text; // // public NewImageComment(final Long imageId, final String author, final String text) { // this.imageId = notNull(imageId); // this.author = notBlank(author); // this.text = notBlank(text); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/Image.java // public class Image { // public final byte[] data; // // public Image(final byte[] data) { // this.data = notNull(data); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/ImageComment.java // public class ImageComment { // // public final Long imageId; // public final String author; // public final String text; // // public ImageComment(final Long imageId, final String author, final String text) { // this.imageId = imageId; // this.author = author; // this.text = text; // } // // @Override // public String toString() { // return "ImageComment{" + // "imageId=" + imageId + // ", author='" + author + '\'' + // ", text='" + text + '\'' + // '}'; // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/ImagePost.java // public class ImagePost { // public final Long id; // public final Title title; // public final NumberOfPoints numPoints; // public final NumberOfComments numComments; // // public ImagePost(final Long id, final Title title, final NumberOfPoints points, final NumberOfComments numComments) { // this.id = notNull(id); // this.title = notNull(title); // this.numPoints = notNull(points); // this.numComments = notNull(numComments); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/Title.java // public class Title { // private static final int MAN_LENGTH = 100; // // public final String value; // // public Title(final String value) { // this.value = notBlank(value); // isTrue(this.value.length() < MAN_LENGTH, "Title can be maximum 100 characters"); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/repository/CommentRepository.java // public interface CommentRepository { // List<ImageComment> findByImageId(final Long id); // // void addComment(Long imageId, String author, String text); // } // // Path: src/main/java/se/omegapoint/facepalm/domain/repository/ImageRepository.java // public interface ImageRepository { // List<ImagePost> findAll(); // // Optional<ImagePost> findById(String id); // // void addImagePost(Title title, byte[] data); // // Image findImageByPostId(Long id); // }
import static org.apache.commons.lang3.Validate.notBlank; import static org.apache.commons.lang3.Validate.notNull; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import se.omegapoint.facepalm.application.transfer.NewImageComment; import se.omegapoint.facepalm.domain.Image; import se.omegapoint.facepalm.domain.ImageComment; import se.omegapoint.facepalm.domain.ImagePost; import se.omegapoint.facepalm.domain.Title; import se.omegapoint.facepalm.domain.repository.CommentRepository; import se.omegapoint.facepalm.domain.repository.ImageRepository; import java.util.List; import java.util.Optional; import static java.util.stream.Collectors.toList;
/* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.application; @Service public class ImageService { @Autowired private ImageRepository imageRepository; @Autowired private CommentRepository commentRepository; public List<ImagePost> getTopImages() { return imageRepository.findAll(); } public Optional<ImagePost> getImagePost(final String id) { notBlank(id); return imageRepository.findById(id); } public List<ImageComment> getCommentsForImage(final Long id) { notNull(id); return commentRepository.findByImageId(id).stream().collect(toList()); } public void addComment(final NewImageComment newImageComment) { notNull(newImageComment); commentRepository.addComment(newImageComment.imageId, newImageComment.author, newImageComment.text); } public void addImagePost(final Title title, final byte[] data) { notNull(title); notNull(data); imageRepository.addImagePost(title, data); }
// Path: src/main/java/se/omegapoint/facepalm/application/transfer/NewImageComment.java // public class NewImageComment { // public final Long imageId; // public final String author; // public final String text; // // public NewImageComment(final Long imageId, final String author, final String text) { // this.imageId = notNull(imageId); // this.author = notBlank(author); // this.text = notBlank(text); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/Image.java // public class Image { // public final byte[] data; // // public Image(final byte[] data) { // this.data = notNull(data); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/ImageComment.java // public class ImageComment { // // public final Long imageId; // public final String author; // public final String text; // // public ImageComment(final Long imageId, final String author, final String text) { // this.imageId = imageId; // this.author = author; // this.text = text; // } // // @Override // public String toString() { // return "ImageComment{" + // "imageId=" + imageId + // ", author='" + author + '\'' + // ", text='" + text + '\'' + // '}'; // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/ImagePost.java // public class ImagePost { // public final Long id; // public final Title title; // public final NumberOfPoints numPoints; // public final NumberOfComments numComments; // // public ImagePost(final Long id, final Title title, final NumberOfPoints points, final NumberOfComments numComments) { // this.id = notNull(id); // this.title = notNull(title); // this.numPoints = notNull(points); // this.numComments = notNull(numComments); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/Title.java // public class Title { // private static final int MAN_LENGTH = 100; // // public final String value; // // public Title(final String value) { // this.value = notBlank(value); // isTrue(this.value.length() < MAN_LENGTH, "Title can be maximum 100 characters"); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/repository/CommentRepository.java // public interface CommentRepository { // List<ImageComment> findByImageId(final Long id); // // void addComment(Long imageId, String author, String text); // } // // Path: src/main/java/se/omegapoint/facepalm/domain/repository/ImageRepository.java // public interface ImageRepository { // List<ImagePost> findAll(); // // Optional<ImagePost> findById(String id); // // void addImagePost(Title title, byte[] data); // // Image findImageByPostId(Long id); // } // Path: src/main/java/se/omegapoint/facepalm/application/ImageService.java import static org.apache.commons.lang3.Validate.notBlank; import static org.apache.commons.lang3.Validate.notNull; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import se.omegapoint.facepalm.application.transfer.NewImageComment; import se.omegapoint.facepalm.domain.Image; import se.omegapoint.facepalm.domain.ImageComment; import se.omegapoint.facepalm.domain.ImagePost; import se.omegapoint.facepalm.domain.Title; import se.omegapoint.facepalm.domain.repository.CommentRepository; import se.omegapoint.facepalm.domain.repository.ImageRepository; import java.util.List; import java.util.Optional; import static java.util.stream.Collectors.toList; /* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.application; @Service public class ImageService { @Autowired private ImageRepository imageRepository; @Autowired private CommentRepository commentRepository; public List<ImagePost> getTopImages() { return imageRepository.findAll(); } public Optional<ImagePost> getImagePost(final String id) { notBlank(id); return imageRepository.findById(id); } public List<ImageComment> getCommentsForImage(final Long id) { notNull(id); return commentRepository.findByImageId(id).stream().collect(toList()); } public void addComment(final NewImageComment newImageComment) { notNull(newImageComment); commentRepository.addComment(newImageComment.imageId, newImageComment.author, newImageComment.text); } public void addImagePost(final Title title, final byte[] data) { notNull(title); notNull(data); imageRepository.addImagePost(title, data); }
public Image getImageFor(final Long id) {
Omegapoint/facepalm
src/main/java/se/omegapoint/facepalm/client/controllers/UserController.java
// Path: src/main/java/se/omegapoint/facepalm/client/adapters/OperationResult.java // public class OperationResult { // private final String message; // private final boolean success; // // private OperationResult(final boolean success, final String message) { // this.message = message; // this.success = success; // } // // public static OperationResult success() { // return new OperationResult(true, null); // } // // public static OperationResult failure(final String message) { // return new OperationResult(false, message); // } // // public String message() { // if (success) { // throw new IllegalStateException("No message available for successful operations"); // } // return message; // } // // public boolean isSuccess() { // return success; // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/adapters/UserAdapter.java // @Adapter // public class UserAdapter { // // private final UserService userService; // // @Autowired // public UserAdapter(final UserService userService) { // this.userService = notNull(userService); // } // // public OperationResult registerNewUser(final RegisterCredentials credentials) { // notNull(credentials); // // final Result<UserSuccess, UserFailure> result = userService.registerUser(credentials.getUsername(), credentials.getEmail(), credentials.getFirstname(), // credentials.getLastname(), credentials.getPassword()); // return result.isSuccess() ? success() : failure("User already exists"); // TODO [dh] Proper error mapping! // } // // public Optional<Profile> profileFor(final String username) { // final Result<User, UserFailure> result = userService.getUserWith(username); // return result.isSuccess() ? Optional.of(new Profile(result.success())) : Optional.empty(); // } // // public Profile profileForCurrentUser() { // final AuthenticatedUser authenticatedUser = (AuthenticatedUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); // final Result<User, UserFailure> result = userService.getUserWith(authenticatedUser.userName); // return new Profile(result.success()); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/RegisterCredentials.java // public class RegisterCredentials { // // @Length(min = 3, max = 20, message = "Username must be between 3 and 20 characters") // private String username; // // @Length(min = 2, max = 40, message = "Firstname must be between 2 and 40 characters") // private String firstname; // // @Length(min = 2, max = 40, message = "Firstname must be between 2 and 40 characters") // private String lastname; // // @NotBlank // @Email(message = "Invalid email format") // private String email; // // @NotBlank // private String password; // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getFirstname() { // return firstname; // } // // public void setFirstname(final String firstname) { // this.firstname = firstname; // } // // public String getLastname() { // return lastname; // } // // public void setLastname(final String lastname) { // this.lastname = lastname; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public void resetPasswords() { // password = null; // } // }
import static org.apache.commons.lang3.Validate.notNull; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import se.omegapoint.facepalm.client.adapters.OperationResult; import se.omegapoint.facepalm.client.adapters.UserAdapter; import se.omegapoint.facepalm.client.models.RegisterCredentials; import javax.validation.Valid;
/* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.client.controllers; @Controller public class UserController {
// Path: src/main/java/se/omegapoint/facepalm/client/adapters/OperationResult.java // public class OperationResult { // private final String message; // private final boolean success; // // private OperationResult(final boolean success, final String message) { // this.message = message; // this.success = success; // } // // public static OperationResult success() { // return new OperationResult(true, null); // } // // public static OperationResult failure(final String message) { // return new OperationResult(false, message); // } // // public String message() { // if (success) { // throw new IllegalStateException("No message available for successful operations"); // } // return message; // } // // public boolean isSuccess() { // return success; // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/adapters/UserAdapter.java // @Adapter // public class UserAdapter { // // private final UserService userService; // // @Autowired // public UserAdapter(final UserService userService) { // this.userService = notNull(userService); // } // // public OperationResult registerNewUser(final RegisterCredentials credentials) { // notNull(credentials); // // final Result<UserSuccess, UserFailure> result = userService.registerUser(credentials.getUsername(), credentials.getEmail(), credentials.getFirstname(), // credentials.getLastname(), credentials.getPassword()); // return result.isSuccess() ? success() : failure("User already exists"); // TODO [dh] Proper error mapping! // } // // public Optional<Profile> profileFor(final String username) { // final Result<User, UserFailure> result = userService.getUserWith(username); // return result.isSuccess() ? Optional.of(new Profile(result.success())) : Optional.empty(); // } // // public Profile profileForCurrentUser() { // final AuthenticatedUser authenticatedUser = (AuthenticatedUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); // final Result<User, UserFailure> result = userService.getUserWith(authenticatedUser.userName); // return new Profile(result.success()); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/RegisterCredentials.java // public class RegisterCredentials { // // @Length(min = 3, max = 20, message = "Username must be between 3 and 20 characters") // private String username; // // @Length(min = 2, max = 40, message = "Firstname must be between 2 and 40 characters") // private String firstname; // // @Length(min = 2, max = 40, message = "Firstname must be between 2 and 40 characters") // private String lastname; // // @NotBlank // @Email(message = "Invalid email format") // private String email; // // @NotBlank // private String password; // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getFirstname() { // return firstname; // } // // public void setFirstname(final String firstname) { // this.firstname = firstname; // } // // public String getLastname() { // return lastname; // } // // public void setLastname(final String lastname) { // this.lastname = lastname; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public void resetPasswords() { // password = null; // } // } // Path: src/main/java/se/omegapoint/facepalm/client/controllers/UserController.java import static org.apache.commons.lang3.Validate.notNull; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import se.omegapoint.facepalm.client.adapters.OperationResult; import se.omegapoint.facepalm.client.adapters.UserAdapter; import se.omegapoint.facepalm.client.models.RegisterCredentials; import javax.validation.Valid; /* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.client.controllers; @Controller public class UserController {
private final UserAdapter userAdapter;
Omegapoint/facepalm
src/main/java/se/omegapoint/facepalm/client/controllers/UserController.java
// Path: src/main/java/se/omegapoint/facepalm/client/adapters/OperationResult.java // public class OperationResult { // private final String message; // private final boolean success; // // private OperationResult(final boolean success, final String message) { // this.message = message; // this.success = success; // } // // public static OperationResult success() { // return new OperationResult(true, null); // } // // public static OperationResult failure(final String message) { // return new OperationResult(false, message); // } // // public String message() { // if (success) { // throw new IllegalStateException("No message available for successful operations"); // } // return message; // } // // public boolean isSuccess() { // return success; // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/adapters/UserAdapter.java // @Adapter // public class UserAdapter { // // private final UserService userService; // // @Autowired // public UserAdapter(final UserService userService) { // this.userService = notNull(userService); // } // // public OperationResult registerNewUser(final RegisterCredentials credentials) { // notNull(credentials); // // final Result<UserSuccess, UserFailure> result = userService.registerUser(credentials.getUsername(), credentials.getEmail(), credentials.getFirstname(), // credentials.getLastname(), credentials.getPassword()); // return result.isSuccess() ? success() : failure("User already exists"); // TODO [dh] Proper error mapping! // } // // public Optional<Profile> profileFor(final String username) { // final Result<User, UserFailure> result = userService.getUserWith(username); // return result.isSuccess() ? Optional.of(new Profile(result.success())) : Optional.empty(); // } // // public Profile profileForCurrentUser() { // final AuthenticatedUser authenticatedUser = (AuthenticatedUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); // final Result<User, UserFailure> result = userService.getUserWith(authenticatedUser.userName); // return new Profile(result.success()); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/RegisterCredentials.java // public class RegisterCredentials { // // @Length(min = 3, max = 20, message = "Username must be between 3 and 20 characters") // private String username; // // @Length(min = 2, max = 40, message = "Firstname must be between 2 and 40 characters") // private String firstname; // // @Length(min = 2, max = 40, message = "Firstname must be between 2 and 40 characters") // private String lastname; // // @NotBlank // @Email(message = "Invalid email format") // private String email; // // @NotBlank // private String password; // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getFirstname() { // return firstname; // } // // public void setFirstname(final String firstname) { // this.firstname = firstname; // } // // public String getLastname() { // return lastname; // } // // public void setLastname(final String lastname) { // this.lastname = lastname; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public void resetPasswords() { // password = null; // } // }
import static org.apache.commons.lang3.Validate.notNull; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import se.omegapoint.facepalm.client.adapters.OperationResult; import se.omegapoint.facepalm.client.adapters.UserAdapter; import se.omegapoint.facepalm.client.models.RegisterCredentials; import javax.validation.Valid;
/* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.client.controllers; @Controller public class UserController { private final UserAdapter userAdapter; @Autowired public UserController(final UserAdapter userAdapter) { this.userAdapter = notNull(userAdapter); } @RequestMapping(value = "/login", method = RequestMethod.GET) public String login(final Model model) { if (userIsLoggedIn()) { return "redirect:/"; }
// Path: src/main/java/se/omegapoint/facepalm/client/adapters/OperationResult.java // public class OperationResult { // private final String message; // private final boolean success; // // private OperationResult(final boolean success, final String message) { // this.message = message; // this.success = success; // } // // public static OperationResult success() { // return new OperationResult(true, null); // } // // public static OperationResult failure(final String message) { // return new OperationResult(false, message); // } // // public String message() { // if (success) { // throw new IllegalStateException("No message available for successful operations"); // } // return message; // } // // public boolean isSuccess() { // return success; // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/adapters/UserAdapter.java // @Adapter // public class UserAdapter { // // private final UserService userService; // // @Autowired // public UserAdapter(final UserService userService) { // this.userService = notNull(userService); // } // // public OperationResult registerNewUser(final RegisterCredentials credentials) { // notNull(credentials); // // final Result<UserSuccess, UserFailure> result = userService.registerUser(credentials.getUsername(), credentials.getEmail(), credentials.getFirstname(), // credentials.getLastname(), credentials.getPassword()); // return result.isSuccess() ? success() : failure("User already exists"); // TODO [dh] Proper error mapping! // } // // public Optional<Profile> profileFor(final String username) { // final Result<User, UserFailure> result = userService.getUserWith(username); // return result.isSuccess() ? Optional.of(new Profile(result.success())) : Optional.empty(); // } // // public Profile profileForCurrentUser() { // final AuthenticatedUser authenticatedUser = (AuthenticatedUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); // final Result<User, UserFailure> result = userService.getUserWith(authenticatedUser.userName); // return new Profile(result.success()); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/RegisterCredentials.java // public class RegisterCredentials { // // @Length(min = 3, max = 20, message = "Username must be between 3 and 20 characters") // private String username; // // @Length(min = 2, max = 40, message = "Firstname must be between 2 and 40 characters") // private String firstname; // // @Length(min = 2, max = 40, message = "Firstname must be between 2 and 40 characters") // private String lastname; // // @NotBlank // @Email(message = "Invalid email format") // private String email; // // @NotBlank // private String password; // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getFirstname() { // return firstname; // } // // public void setFirstname(final String firstname) { // this.firstname = firstname; // } // // public String getLastname() { // return lastname; // } // // public void setLastname(final String lastname) { // this.lastname = lastname; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public void resetPasswords() { // password = null; // } // } // Path: src/main/java/se/omegapoint/facepalm/client/controllers/UserController.java import static org.apache.commons.lang3.Validate.notNull; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import se.omegapoint.facepalm.client.adapters.OperationResult; import se.omegapoint.facepalm.client.adapters.UserAdapter; import se.omegapoint.facepalm.client.models.RegisterCredentials; import javax.validation.Valid; /* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.client.controllers; @Controller public class UserController { private final UserAdapter userAdapter; @Autowired public UserController(final UserAdapter userAdapter) { this.userAdapter = notNull(userAdapter); } @RequestMapping(value = "/login", method = RequestMethod.GET) public String login(final Model model) { if (userIsLoggedIn()) { return "redirect:/"; }
model.addAttribute("registerCredentials", new RegisterCredentials());
Omegapoint/facepalm
src/main/java/se/omegapoint/facepalm/client/controllers/UserController.java
// Path: src/main/java/se/omegapoint/facepalm/client/adapters/OperationResult.java // public class OperationResult { // private final String message; // private final boolean success; // // private OperationResult(final boolean success, final String message) { // this.message = message; // this.success = success; // } // // public static OperationResult success() { // return new OperationResult(true, null); // } // // public static OperationResult failure(final String message) { // return new OperationResult(false, message); // } // // public String message() { // if (success) { // throw new IllegalStateException("No message available for successful operations"); // } // return message; // } // // public boolean isSuccess() { // return success; // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/adapters/UserAdapter.java // @Adapter // public class UserAdapter { // // private final UserService userService; // // @Autowired // public UserAdapter(final UserService userService) { // this.userService = notNull(userService); // } // // public OperationResult registerNewUser(final RegisterCredentials credentials) { // notNull(credentials); // // final Result<UserSuccess, UserFailure> result = userService.registerUser(credentials.getUsername(), credentials.getEmail(), credentials.getFirstname(), // credentials.getLastname(), credentials.getPassword()); // return result.isSuccess() ? success() : failure("User already exists"); // TODO [dh] Proper error mapping! // } // // public Optional<Profile> profileFor(final String username) { // final Result<User, UserFailure> result = userService.getUserWith(username); // return result.isSuccess() ? Optional.of(new Profile(result.success())) : Optional.empty(); // } // // public Profile profileForCurrentUser() { // final AuthenticatedUser authenticatedUser = (AuthenticatedUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); // final Result<User, UserFailure> result = userService.getUserWith(authenticatedUser.userName); // return new Profile(result.success()); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/RegisterCredentials.java // public class RegisterCredentials { // // @Length(min = 3, max = 20, message = "Username must be between 3 and 20 characters") // private String username; // // @Length(min = 2, max = 40, message = "Firstname must be between 2 and 40 characters") // private String firstname; // // @Length(min = 2, max = 40, message = "Firstname must be between 2 and 40 characters") // private String lastname; // // @NotBlank // @Email(message = "Invalid email format") // private String email; // // @NotBlank // private String password; // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getFirstname() { // return firstname; // } // // public void setFirstname(final String firstname) { // this.firstname = firstname; // } // // public String getLastname() { // return lastname; // } // // public void setLastname(final String lastname) { // this.lastname = lastname; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public void resetPasswords() { // password = null; // } // }
import static org.apache.commons.lang3.Validate.notNull; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import se.omegapoint.facepalm.client.adapters.OperationResult; import se.omegapoint.facepalm.client.adapters.UserAdapter; import se.omegapoint.facepalm.client.models.RegisterCredentials; import javax.validation.Valid;
/* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.client.controllers; @Controller public class UserController { private final UserAdapter userAdapter; @Autowired public UserController(final UserAdapter userAdapter) { this.userAdapter = notNull(userAdapter); } @RequestMapping(value = "/login", method = RequestMethod.GET) public String login(final Model model) { if (userIsLoggedIn()) { return "redirect:/"; } model.addAttribute("registerCredentials", new RegisterCredentials()); return "login"; } @RequestMapping(value = "/register", method = RequestMethod.POST) public String register(final @Valid RegisterCredentials credentials, final BindingResult bindingResult, final Model model) { if (bindingResult.hasErrors()) { credentials.resetPasswords(); return "login"; }
// Path: src/main/java/se/omegapoint/facepalm/client/adapters/OperationResult.java // public class OperationResult { // private final String message; // private final boolean success; // // private OperationResult(final boolean success, final String message) { // this.message = message; // this.success = success; // } // // public static OperationResult success() { // return new OperationResult(true, null); // } // // public static OperationResult failure(final String message) { // return new OperationResult(false, message); // } // // public String message() { // if (success) { // throw new IllegalStateException("No message available for successful operations"); // } // return message; // } // // public boolean isSuccess() { // return success; // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/adapters/UserAdapter.java // @Adapter // public class UserAdapter { // // private final UserService userService; // // @Autowired // public UserAdapter(final UserService userService) { // this.userService = notNull(userService); // } // // public OperationResult registerNewUser(final RegisterCredentials credentials) { // notNull(credentials); // // final Result<UserSuccess, UserFailure> result = userService.registerUser(credentials.getUsername(), credentials.getEmail(), credentials.getFirstname(), // credentials.getLastname(), credentials.getPassword()); // return result.isSuccess() ? success() : failure("User already exists"); // TODO [dh] Proper error mapping! // } // // public Optional<Profile> profileFor(final String username) { // final Result<User, UserFailure> result = userService.getUserWith(username); // return result.isSuccess() ? Optional.of(new Profile(result.success())) : Optional.empty(); // } // // public Profile profileForCurrentUser() { // final AuthenticatedUser authenticatedUser = (AuthenticatedUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); // final Result<User, UserFailure> result = userService.getUserWith(authenticatedUser.userName); // return new Profile(result.success()); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/RegisterCredentials.java // public class RegisterCredentials { // // @Length(min = 3, max = 20, message = "Username must be between 3 and 20 characters") // private String username; // // @Length(min = 2, max = 40, message = "Firstname must be between 2 and 40 characters") // private String firstname; // // @Length(min = 2, max = 40, message = "Firstname must be between 2 and 40 characters") // private String lastname; // // @NotBlank // @Email(message = "Invalid email format") // private String email; // // @NotBlank // private String password; // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getFirstname() { // return firstname; // } // // public void setFirstname(final String firstname) { // this.firstname = firstname; // } // // public String getLastname() { // return lastname; // } // // public void setLastname(final String lastname) { // this.lastname = lastname; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public void resetPasswords() { // password = null; // } // } // Path: src/main/java/se/omegapoint/facepalm/client/controllers/UserController.java import static org.apache.commons.lang3.Validate.notNull; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import se.omegapoint.facepalm.client.adapters.OperationResult; import se.omegapoint.facepalm.client.adapters.UserAdapter; import se.omegapoint.facepalm.client.models.RegisterCredentials; import javax.validation.Valid; /* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.client.controllers; @Controller public class UserController { private final UserAdapter userAdapter; @Autowired public UserController(final UserAdapter userAdapter) { this.userAdapter = notNull(userAdapter); } @RequestMapping(value = "/login", method = RequestMethod.GET) public String login(final Model model) { if (userIsLoggedIn()) { return "redirect:/"; } model.addAttribute("registerCredentials", new RegisterCredentials()); return "login"; } @RequestMapping(value = "/register", method = RequestMethod.POST) public String register(final @Valid RegisterCredentials credentials, final BindingResult bindingResult, final Model model) { if (bindingResult.hasErrors()) { credentials.resetPasswords(); return "login"; }
final OperationResult result = userAdapter.registerNewUser(credentials);
Omegapoint/facepalm
src/main/java/se/omegapoint/facepalm/application/DocumentService.java
// Path: src/main/java/se/omegapoint/facepalm/domain/Document.java // public class Document { // public final Long id; // public final String filename; // public final Long fileSize; // public final LocalDateTime uploadedDate; // // public Document(final Long id, final String filename, final Long fileSize, final LocalDateTime uploadedDate) { // this.id = id; // this.filename = filename; // this.fileSize = fileSize; // this.uploadedDate = uploadedDate; // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/repository/DocumentRepository.java // public interface DocumentRepository { // List<Document> findAllFor(String user); // }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import se.omegapoint.facepalm.domain.Document; import se.omegapoint.facepalm.domain.repository.DocumentRepository; import java.util.List; import static org.apache.commons.lang3.Validate.notBlank; import static org.apache.commons.lang3.Validate.notNull;
/* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.application; @Service public class DocumentService {
// Path: src/main/java/se/omegapoint/facepalm/domain/Document.java // public class Document { // public final Long id; // public final String filename; // public final Long fileSize; // public final LocalDateTime uploadedDate; // // public Document(final Long id, final String filename, final Long fileSize, final LocalDateTime uploadedDate) { // this.id = id; // this.filename = filename; // this.fileSize = fileSize; // this.uploadedDate = uploadedDate; // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/repository/DocumentRepository.java // public interface DocumentRepository { // List<Document> findAllFor(String user); // } // Path: src/main/java/se/omegapoint/facepalm/application/DocumentService.java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import se.omegapoint.facepalm.domain.Document; import se.omegapoint.facepalm.domain.repository.DocumentRepository; import java.util.List; import static org.apache.commons.lang3.Validate.notBlank; import static org.apache.commons.lang3.Validate.notNull; /* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.application; @Service public class DocumentService {
private DocumentRepository documentRepository;
Omegapoint/facepalm
src/main/java/se/omegapoint/facepalm/application/DocumentService.java
// Path: src/main/java/se/omegapoint/facepalm/domain/Document.java // public class Document { // public final Long id; // public final String filename; // public final Long fileSize; // public final LocalDateTime uploadedDate; // // public Document(final Long id, final String filename, final Long fileSize, final LocalDateTime uploadedDate) { // this.id = id; // this.filename = filename; // this.fileSize = fileSize; // this.uploadedDate = uploadedDate; // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/repository/DocumentRepository.java // public interface DocumentRepository { // List<Document> findAllFor(String user); // }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import se.omegapoint.facepalm.domain.Document; import se.omegapoint.facepalm.domain.repository.DocumentRepository; import java.util.List; import static org.apache.commons.lang3.Validate.notBlank; import static org.apache.commons.lang3.Validate.notNull;
/* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.application; @Service public class DocumentService { private DocumentRepository documentRepository; @Autowired public DocumentService(final DocumentRepository documentRepository) { this.documentRepository = notNull(documentRepository); }
// Path: src/main/java/se/omegapoint/facepalm/domain/Document.java // public class Document { // public final Long id; // public final String filename; // public final Long fileSize; // public final LocalDateTime uploadedDate; // // public Document(final Long id, final String filename, final Long fileSize, final LocalDateTime uploadedDate) { // this.id = id; // this.filename = filename; // this.fileSize = fileSize; // this.uploadedDate = uploadedDate; // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/repository/DocumentRepository.java // public interface DocumentRepository { // List<Document> findAllFor(String user); // } // Path: src/main/java/se/omegapoint/facepalm/application/DocumentService.java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import se.omegapoint.facepalm.domain.Document; import se.omegapoint.facepalm.domain.repository.DocumentRepository; import java.util.List; import static org.apache.commons.lang3.Validate.notBlank; import static org.apache.commons.lang3.Validate.notNull; /* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.application; @Service public class DocumentService { private DocumentRepository documentRepository; @Autowired public DocumentService(final DocumentRepository documentRepository) { this.documentRepository = notNull(documentRepository); }
public List<Document> documentsForUser(final String user) {
Omegapoint/facepalm
src/main/java/se/omegapoint/facepalm/client/config/EventServiceConfig.java
// Path: src/main/java/se/omegapoint/facepalm/domain/event/EventService.java // public interface EventService { // void publish(ApplicationEvent event); // } // // Path: src/main/java/se/omegapoint/facepalm/infrastructure/event/ApplicationEventLogger.java // public final class ApplicationEventLogger implements Consumer<Event<GenericEvent>> { // private final Logger logger = LoggerFactory.getLogger(getClass()); // // @Override // public void accept(final Event<GenericEvent> event) { // notNull(event); // logger.info(event.getData().message()); // } // } // // Path: src/main/java/se/omegapoint/facepalm/infrastructure/event/ReactorEventService.java // public class ReactorEventService implements EventService { // // private final EventBus eventBus; // // public ReactorEventService(final EventBus eventBus) { // this.eventBus = notNull(eventBus); // } // // public void publish(final ApplicationEvent event) { // notNull(event); // eventBus.notify(GLOBAL.channel, Event.wrap(event)); // } // // public <E extends ApplicationEvent> void register(final Selector channel, final Consumer<Event<E>> eventListener) { // notNull(eventListener); // notNull(channel); // eventBus.on(channel, eventListener); // } // }
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import reactor.bus.EventBus; import se.omegapoint.facepalm.domain.event.EventService; import se.omegapoint.facepalm.infrastructure.event.ApplicationEventLogger; import se.omegapoint.facepalm.infrastructure.event.ReactorEventService; import static se.omegapoint.facepalm.infrastructure.event.EventChannel.GLOBAL;
/* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.client.config; @Configuration public class EventServiceConfig { @Bean
// Path: src/main/java/se/omegapoint/facepalm/domain/event/EventService.java // public interface EventService { // void publish(ApplicationEvent event); // } // // Path: src/main/java/se/omegapoint/facepalm/infrastructure/event/ApplicationEventLogger.java // public final class ApplicationEventLogger implements Consumer<Event<GenericEvent>> { // private final Logger logger = LoggerFactory.getLogger(getClass()); // // @Override // public void accept(final Event<GenericEvent> event) { // notNull(event); // logger.info(event.getData().message()); // } // } // // Path: src/main/java/se/omegapoint/facepalm/infrastructure/event/ReactorEventService.java // public class ReactorEventService implements EventService { // // private final EventBus eventBus; // // public ReactorEventService(final EventBus eventBus) { // this.eventBus = notNull(eventBus); // } // // public void publish(final ApplicationEvent event) { // notNull(event); // eventBus.notify(GLOBAL.channel, Event.wrap(event)); // } // // public <E extends ApplicationEvent> void register(final Selector channel, final Consumer<Event<E>> eventListener) { // notNull(eventListener); // notNull(channel); // eventBus.on(channel, eventListener); // } // } // Path: src/main/java/se/omegapoint/facepalm/client/config/EventServiceConfig.java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import reactor.bus.EventBus; import se.omegapoint.facepalm.domain.event.EventService; import se.omegapoint.facepalm.infrastructure.event.ApplicationEventLogger; import se.omegapoint.facepalm.infrastructure.event.ReactorEventService; import static se.omegapoint.facepalm.infrastructure.event.EventChannel.GLOBAL; /* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.client.config; @Configuration public class EventServiceConfig { @Bean
public EventService eventService() {
Omegapoint/facepalm
src/main/java/se/omegapoint/facepalm/client/config/EventServiceConfig.java
// Path: src/main/java/se/omegapoint/facepalm/domain/event/EventService.java // public interface EventService { // void publish(ApplicationEvent event); // } // // Path: src/main/java/se/omegapoint/facepalm/infrastructure/event/ApplicationEventLogger.java // public final class ApplicationEventLogger implements Consumer<Event<GenericEvent>> { // private final Logger logger = LoggerFactory.getLogger(getClass()); // // @Override // public void accept(final Event<GenericEvent> event) { // notNull(event); // logger.info(event.getData().message()); // } // } // // Path: src/main/java/se/omegapoint/facepalm/infrastructure/event/ReactorEventService.java // public class ReactorEventService implements EventService { // // private final EventBus eventBus; // // public ReactorEventService(final EventBus eventBus) { // this.eventBus = notNull(eventBus); // } // // public void publish(final ApplicationEvent event) { // notNull(event); // eventBus.notify(GLOBAL.channel, Event.wrap(event)); // } // // public <E extends ApplicationEvent> void register(final Selector channel, final Consumer<Event<E>> eventListener) { // notNull(eventListener); // notNull(channel); // eventBus.on(channel, eventListener); // } // }
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import reactor.bus.EventBus; import se.omegapoint.facepalm.domain.event.EventService; import se.omegapoint.facepalm.infrastructure.event.ApplicationEventLogger; import se.omegapoint.facepalm.infrastructure.event.ReactorEventService; import static se.omegapoint.facepalm.infrastructure.event.EventChannel.GLOBAL;
/* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.client.config; @Configuration public class EventServiceConfig { @Bean public EventService eventService() {
// Path: src/main/java/se/omegapoint/facepalm/domain/event/EventService.java // public interface EventService { // void publish(ApplicationEvent event); // } // // Path: src/main/java/se/omegapoint/facepalm/infrastructure/event/ApplicationEventLogger.java // public final class ApplicationEventLogger implements Consumer<Event<GenericEvent>> { // private final Logger logger = LoggerFactory.getLogger(getClass()); // // @Override // public void accept(final Event<GenericEvent> event) { // notNull(event); // logger.info(event.getData().message()); // } // } // // Path: src/main/java/se/omegapoint/facepalm/infrastructure/event/ReactorEventService.java // public class ReactorEventService implements EventService { // // private final EventBus eventBus; // // public ReactorEventService(final EventBus eventBus) { // this.eventBus = notNull(eventBus); // } // // public void publish(final ApplicationEvent event) { // notNull(event); // eventBus.notify(GLOBAL.channel, Event.wrap(event)); // } // // public <E extends ApplicationEvent> void register(final Selector channel, final Consumer<Event<E>> eventListener) { // notNull(eventListener); // notNull(channel); // eventBus.on(channel, eventListener); // } // } // Path: src/main/java/se/omegapoint/facepalm/client/config/EventServiceConfig.java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import reactor.bus.EventBus; import se.omegapoint.facepalm.domain.event.EventService; import se.omegapoint.facepalm.infrastructure.event.ApplicationEventLogger; import se.omegapoint.facepalm.infrastructure.event.ReactorEventService; import static se.omegapoint.facepalm.infrastructure.event.EventChannel.GLOBAL; /* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.client.config; @Configuration public class EventServiceConfig { @Bean public EventService eventService() {
final ReactorEventService eventService = new ReactorEventService(EventBus.create());
Omegapoint/facepalm
src/main/java/se/omegapoint/facepalm/client/config/EventServiceConfig.java
// Path: src/main/java/se/omegapoint/facepalm/domain/event/EventService.java // public interface EventService { // void publish(ApplicationEvent event); // } // // Path: src/main/java/se/omegapoint/facepalm/infrastructure/event/ApplicationEventLogger.java // public final class ApplicationEventLogger implements Consumer<Event<GenericEvent>> { // private final Logger logger = LoggerFactory.getLogger(getClass()); // // @Override // public void accept(final Event<GenericEvent> event) { // notNull(event); // logger.info(event.getData().message()); // } // } // // Path: src/main/java/se/omegapoint/facepalm/infrastructure/event/ReactorEventService.java // public class ReactorEventService implements EventService { // // private final EventBus eventBus; // // public ReactorEventService(final EventBus eventBus) { // this.eventBus = notNull(eventBus); // } // // public void publish(final ApplicationEvent event) { // notNull(event); // eventBus.notify(GLOBAL.channel, Event.wrap(event)); // } // // public <E extends ApplicationEvent> void register(final Selector channel, final Consumer<Event<E>> eventListener) { // notNull(eventListener); // notNull(channel); // eventBus.on(channel, eventListener); // } // }
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import reactor.bus.EventBus; import se.omegapoint.facepalm.domain.event.EventService; import se.omegapoint.facepalm.infrastructure.event.ApplicationEventLogger; import se.omegapoint.facepalm.infrastructure.event.ReactorEventService; import static se.omegapoint.facepalm.infrastructure.event.EventChannel.GLOBAL;
/* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.client.config; @Configuration public class EventServiceConfig { @Bean public EventService eventService() { final ReactorEventService eventService = new ReactorEventService(EventBus.create());
// Path: src/main/java/se/omegapoint/facepalm/domain/event/EventService.java // public interface EventService { // void publish(ApplicationEvent event); // } // // Path: src/main/java/se/omegapoint/facepalm/infrastructure/event/ApplicationEventLogger.java // public final class ApplicationEventLogger implements Consumer<Event<GenericEvent>> { // private final Logger logger = LoggerFactory.getLogger(getClass()); // // @Override // public void accept(final Event<GenericEvent> event) { // notNull(event); // logger.info(event.getData().message()); // } // } // // Path: src/main/java/se/omegapoint/facepalm/infrastructure/event/ReactorEventService.java // public class ReactorEventService implements EventService { // // private final EventBus eventBus; // // public ReactorEventService(final EventBus eventBus) { // this.eventBus = notNull(eventBus); // } // // public void publish(final ApplicationEvent event) { // notNull(event); // eventBus.notify(GLOBAL.channel, Event.wrap(event)); // } // // public <E extends ApplicationEvent> void register(final Selector channel, final Consumer<Event<E>> eventListener) { // notNull(eventListener); // notNull(channel); // eventBus.on(channel, eventListener); // } // } // Path: src/main/java/se/omegapoint/facepalm/client/config/EventServiceConfig.java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import reactor.bus.EventBus; import se.omegapoint.facepalm.domain.event.EventService; import se.omegapoint.facepalm.infrastructure.event.ApplicationEventLogger; import se.omegapoint.facepalm.infrastructure.event.ReactorEventService; import static se.omegapoint.facepalm.infrastructure.event.EventChannel.GLOBAL; /* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.client.config; @Configuration public class EventServiceConfig { @Bean public EventService eventService() { final ReactorEventService eventService = new ReactorEventService(EventBus.create());
eventService.register(GLOBAL.channel(), new ApplicationEventLogger());
Omegapoint/facepalm
src/main/java/se/omegapoint/facepalm/client/adapters/ImageAdapter.java
// Path: src/main/java/se/omegapoint/facepalm/application/ImageService.java // @Service // public class ImageService { // // @Autowired // private ImageRepository imageRepository; // // @Autowired // private CommentRepository commentRepository; // // public List<ImagePost> getTopImages() { // return imageRepository.findAll(); // } // // public Optional<ImagePost> getImagePost(final String id) { // notBlank(id); // // return imageRepository.findById(id); // } // // public List<ImageComment> getCommentsForImage(final Long id) { // notNull(id); // // return commentRepository.findByImageId(id).stream().collect(toList()); // } // // public void addComment(final NewImageComment newImageComment) { // notNull(newImageComment); // // commentRepository.addComment(newImageComment.imageId, newImageComment.author, newImageComment.text); // } // // public void addImagePost(final Title title, final byte[] data) { // notNull(title); // notNull(data); // imageRepository.addImagePost(title, data); // } // // public Image getImageFor(final Long id) { // notNull(id); // return imageRepository.findImageByPostId(id); // } // } // // Path: src/main/java/se/omegapoint/facepalm/application/transfer/NewImageComment.java // public class NewImageComment { // public final Long imageId; // public final String author; // public final String text; // // public NewImageComment(final Long imageId, final String author, final String text) { // this.imageId = notNull(imageId); // this.author = notBlank(author); // this.text = notBlank(text); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/ImageComment.java // public class ImageComment { // public final String author; // public final String text; // // public ImageComment(final String author, final String text) { // this.author = author; // this.text = text; // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/ImagePost.java // public class ImagePost { // public final Long id; // public final String title; // public final Long numPoints; // public final Long numComments; // // public ImagePost(final Long id, final String title, final Long points, final Long numComments) { // this.id = notNull(id); // this.title = notBlank(title); // this.numPoints = notNull(points); // this.numComments = notNull(numComments); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/ImageUpload.java // public class ImageUpload { // public final String title; // public final byte[] data; // // public ImageUpload(final String title, final byte[] data) { // this.title = notBlank(title); // this.data = notNull(data); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/security/AuthenticatedUser.java // public class AuthenticatedUser { // public final String userName; // // public AuthenticatedUser(final String userName) { // this.userName = notBlank(userName); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/Image.java // public class Image { // public final byte[] data; // // public Image(final byte[] data) { // this.data = notNull(data); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/Title.java // public class Title { // private static final int MAN_LENGTH = 100; // // public final String value; // // public Title(final String value) { // this.value = notBlank(value); // isTrue(this.value.length() < MAN_LENGTH, "Title can be maximum 100 characters"); // } // }
import static java.util.stream.Collectors.toList; import static org.apache.commons.lang3.Validate.notBlank; import static org.apache.commons.lang3.Validate.notNull; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.context.SecurityContextHolder; import se.omegapoint.facepalm.application.ImageService; import se.omegapoint.facepalm.application.transfer.NewImageComment; import se.omegapoint.facepalm.client.config.Adapter; import se.omegapoint.facepalm.client.models.ImageComment; import se.omegapoint.facepalm.client.models.ImagePost; import se.omegapoint.facepalm.client.models.ImageUpload; import se.omegapoint.facepalm.client.security.AuthenticatedUser; import se.omegapoint.facepalm.domain.Image; import se.omegapoint.facepalm.domain.Title; import java.util.List; import java.util.Optional;
/* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.client.adapters; @Adapter public class ImageAdapter {
// Path: src/main/java/se/omegapoint/facepalm/application/ImageService.java // @Service // public class ImageService { // // @Autowired // private ImageRepository imageRepository; // // @Autowired // private CommentRepository commentRepository; // // public List<ImagePost> getTopImages() { // return imageRepository.findAll(); // } // // public Optional<ImagePost> getImagePost(final String id) { // notBlank(id); // // return imageRepository.findById(id); // } // // public List<ImageComment> getCommentsForImage(final Long id) { // notNull(id); // // return commentRepository.findByImageId(id).stream().collect(toList()); // } // // public void addComment(final NewImageComment newImageComment) { // notNull(newImageComment); // // commentRepository.addComment(newImageComment.imageId, newImageComment.author, newImageComment.text); // } // // public void addImagePost(final Title title, final byte[] data) { // notNull(title); // notNull(data); // imageRepository.addImagePost(title, data); // } // // public Image getImageFor(final Long id) { // notNull(id); // return imageRepository.findImageByPostId(id); // } // } // // Path: src/main/java/se/omegapoint/facepalm/application/transfer/NewImageComment.java // public class NewImageComment { // public final Long imageId; // public final String author; // public final String text; // // public NewImageComment(final Long imageId, final String author, final String text) { // this.imageId = notNull(imageId); // this.author = notBlank(author); // this.text = notBlank(text); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/ImageComment.java // public class ImageComment { // public final String author; // public final String text; // // public ImageComment(final String author, final String text) { // this.author = author; // this.text = text; // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/ImagePost.java // public class ImagePost { // public final Long id; // public final String title; // public final Long numPoints; // public final Long numComments; // // public ImagePost(final Long id, final String title, final Long points, final Long numComments) { // this.id = notNull(id); // this.title = notBlank(title); // this.numPoints = notNull(points); // this.numComments = notNull(numComments); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/ImageUpload.java // public class ImageUpload { // public final String title; // public final byte[] data; // // public ImageUpload(final String title, final byte[] data) { // this.title = notBlank(title); // this.data = notNull(data); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/security/AuthenticatedUser.java // public class AuthenticatedUser { // public final String userName; // // public AuthenticatedUser(final String userName) { // this.userName = notBlank(userName); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/Image.java // public class Image { // public final byte[] data; // // public Image(final byte[] data) { // this.data = notNull(data); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/Title.java // public class Title { // private static final int MAN_LENGTH = 100; // // public final String value; // // public Title(final String value) { // this.value = notBlank(value); // isTrue(this.value.length() < MAN_LENGTH, "Title can be maximum 100 characters"); // } // } // Path: src/main/java/se/omegapoint/facepalm/client/adapters/ImageAdapter.java import static java.util.stream.Collectors.toList; import static org.apache.commons.lang3.Validate.notBlank; import static org.apache.commons.lang3.Validate.notNull; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.context.SecurityContextHolder; import se.omegapoint.facepalm.application.ImageService; import se.omegapoint.facepalm.application.transfer.NewImageComment; import se.omegapoint.facepalm.client.config.Adapter; import se.omegapoint.facepalm.client.models.ImageComment; import se.omegapoint.facepalm.client.models.ImagePost; import se.omegapoint.facepalm.client.models.ImageUpload; import se.omegapoint.facepalm.client.security.AuthenticatedUser; import se.omegapoint.facepalm.domain.Image; import se.omegapoint.facepalm.domain.Title; import java.util.List; import java.util.Optional; /* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.client.adapters; @Adapter public class ImageAdapter {
private final ImageService imageService;
Omegapoint/facepalm
src/main/java/se/omegapoint/facepalm/client/adapters/ImageAdapter.java
// Path: src/main/java/se/omegapoint/facepalm/application/ImageService.java // @Service // public class ImageService { // // @Autowired // private ImageRepository imageRepository; // // @Autowired // private CommentRepository commentRepository; // // public List<ImagePost> getTopImages() { // return imageRepository.findAll(); // } // // public Optional<ImagePost> getImagePost(final String id) { // notBlank(id); // // return imageRepository.findById(id); // } // // public List<ImageComment> getCommentsForImage(final Long id) { // notNull(id); // // return commentRepository.findByImageId(id).stream().collect(toList()); // } // // public void addComment(final NewImageComment newImageComment) { // notNull(newImageComment); // // commentRepository.addComment(newImageComment.imageId, newImageComment.author, newImageComment.text); // } // // public void addImagePost(final Title title, final byte[] data) { // notNull(title); // notNull(data); // imageRepository.addImagePost(title, data); // } // // public Image getImageFor(final Long id) { // notNull(id); // return imageRepository.findImageByPostId(id); // } // } // // Path: src/main/java/se/omegapoint/facepalm/application/transfer/NewImageComment.java // public class NewImageComment { // public final Long imageId; // public final String author; // public final String text; // // public NewImageComment(final Long imageId, final String author, final String text) { // this.imageId = notNull(imageId); // this.author = notBlank(author); // this.text = notBlank(text); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/ImageComment.java // public class ImageComment { // public final String author; // public final String text; // // public ImageComment(final String author, final String text) { // this.author = author; // this.text = text; // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/ImagePost.java // public class ImagePost { // public final Long id; // public final String title; // public final Long numPoints; // public final Long numComments; // // public ImagePost(final Long id, final String title, final Long points, final Long numComments) { // this.id = notNull(id); // this.title = notBlank(title); // this.numPoints = notNull(points); // this.numComments = notNull(numComments); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/ImageUpload.java // public class ImageUpload { // public final String title; // public final byte[] data; // // public ImageUpload(final String title, final byte[] data) { // this.title = notBlank(title); // this.data = notNull(data); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/security/AuthenticatedUser.java // public class AuthenticatedUser { // public final String userName; // // public AuthenticatedUser(final String userName) { // this.userName = notBlank(userName); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/Image.java // public class Image { // public final byte[] data; // // public Image(final byte[] data) { // this.data = notNull(data); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/Title.java // public class Title { // private static final int MAN_LENGTH = 100; // // public final String value; // // public Title(final String value) { // this.value = notBlank(value); // isTrue(this.value.length() < MAN_LENGTH, "Title can be maximum 100 characters"); // } // }
import static java.util.stream.Collectors.toList; import static org.apache.commons.lang3.Validate.notBlank; import static org.apache.commons.lang3.Validate.notNull; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.context.SecurityContextHolder; import se.omegapoint.facepalm.application.ImageService; import se.omegapoint.facepalm.application.transfer.NewImageComment; import se.omegapoint.facepalm.client.config.Adapter; import se.omegapoint.facepalm.client.models.ImageComment; import se.omegapoint.facepalm.client.models.ImagePost; import se.omegapoint.facepalm.client.models.ImageUpload; import se.omegapoint.facepalm.client.security.AuthenticatedUser; import se.omegapoint.facepalm.domain.Image; import se.omegapoint.facepalm.domain.Title; import java.util.List; import java.util.Optional;
/* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.client.adapters; @Adapter public class ImageAdapter { private final ImageService imageService; @Autowired public ImageAdapter(final ImageService imageService) { this.imageService = notNull(imageService); }
// Path: src/main/java/se/omegapoint/facepalm/application/ImageService.java // @Service // public class ImageService { // // @Autowired // private ImageRepository imageRepository; // // @Autowired // private CommentRepository commentRepository; // // public List<ImagePost> getTopImages() { // return imageRepository.findAll(); // } // // public Optional<ImagePost> getImagePost(final String id) { // notBlank(id); // // return imageRepository.findById(id); // } // // public List<ImageComment> getCommentsForImage(final Long id) { // notNull(id); // // return commentRepository.findByImageId(id).stream().collect(toList()); // } // // public void addComment(final NewImageComment newImageComment) { // notNull(newImageComment); // // commentRepository.addComment(newImageComment.imageId, newImageComment.author, newImageComment.text); // } // // public void addImagePost(final Title title, final byte[] data) { // notNull(title); // notNull(data); // imageRepository.addImagePost(title, data); // } // // public Image getImageFor(final Long id) { // notNull(id); // return imageRepository.findImageByPostId(id); // } // } // // Path: src/main/java/se/omegapoint/facepalm/application/transfer/NewImageComment.java // public class NewImageComment { // public final Long imageId; // public final String author; // public final String text; // // public NewImageComment(final Long imageId, final String author, final String text) { // this.imageId = notNull(imageId); // this.author = notBlank(author); // this.text = notBlank(text); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/ImageComment.java // public class ImageComment { // public final String author; // public final String text; // // public ImageComment(final String author, final String text) { // this.author = author; // this.text = text; // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/ImagePost.java // public class ImagePost { // public final Long id; // public final String title; // public final Long numPoints; // public final Long numComments; // // public ImagePost(final Long id, final String title, final Long points, final Long numComments) { // this.id = notNull(id); // this.title = notBlank(title); // this.numPoints = notNull(points); // this.numComments = notNull(numComments); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/ImageUpload.java // public class ImageUpload { // public final String title; // public final byte[] data; // // public ImageUpload(final String title, final byte[] data) { // this.title = notBlank(title); // this.data = notNull(data); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/security/AuthenticatedUser.java // public class AuthenticatedUser { // public final String userName; // // public AuthenticatedUser(final String userName) { // this.userName = notBlank(userName); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/Image.java // public class Image { // public final byte[] data; // // public Image(final byte[] data) { // this.data = notNull(data); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/Title.java // public class Title { // private static final int MAN_LENGTH = 100; // // public final String value; // // public Title(final String value) { // this.value = notBlank(value); // isTrue(this.value.length() < MAN_LENGTH, "Title can be maximum 100 characters"); // } // } // Path: src/main/java/se/omegapoint/facepalm/client/adapters/ImageAdapter.java import static java.util.stream.Collectors.toList; import static org.apache.commons.lang3.Validate.notBlank; import static org.apache.commons.lang3.Validate.notNull; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.context.SecurityContextHolder; import se.omegapoint.facepalm.application.ImageService; import se.omegapoint.facepalm.application.transfer.NewImageComment; import se.omegapoint.facepalm.client.config.Adapter; import se.omegapoint.facepalm.client.models.ImageComment; import se.omegapoint.facepalm.client.models.ImagePost; import se.omegapoint.facepalm.client.models.ImageUpload; import se.omegapoint.facepalm.client.security.AuthenticatedUser; import se.omegapoint.facepalm.domain.Image; import se.omegapoint.facepalm.domain.Title; import java.util.List; import java.util.Optional; /* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.client.adapters; @Adapter public class ImageAdapter { private final ImageService imageService; @Autowired public ImageAdapter(final ImageService imageService) { this.imageService = notNull(imageService); }
public List<ImagePost> getTopImagePosts() {
Omegapoint/facepalm
src/main/java/se/omegapoint/facepalm/client/adapters/ImageAdapter.java
// Path: src/main/java/se/omegapoint/facepalm/application/ImageService.java // @Service // public class ImageService { // // @Autowired // private ImageRepository imageRepository; // // @Autowired // private CommentRepository commentRepository; // // public List<ImagePost> getTopImages() { // return imageRepository.findAll(); // } // // public Optional<ImagePost> getImagePost(final String id) { // notBlank(id); // // return imageRepository.findById(id); // } // // public List<ImageComment> getCommentsForImage(final Long id) { // notNull(id); // // return commentRepository.findByImageId(id).stream().collect(toList()); // } // // public void addComment(final NewImageComment newImageComment) { // notNull(newImageComment); // // commentRepository.addComment(newImageComment.imageId, newImageComment.author, newImageComment.text); // } // // public void addImagePost(final Title title, final byte[] data) { // notNull(title); // notNull(data); // imageRepository.addImagePost(title, data); // } // // public Image getImageFor(final Long id) { // notNull(id); // return imageRepository.findImageByPostId(id); // } // } // // Path: src/main/java/se/omegapoint/facepalm/application/transfer/NewImageComment.java // public class NewImageComment { // public final Long imageId; // public final String author; // public final String text; // // public NewImageComment(final Long imageId, final String author, final String text) { // this.imageId = notNull(imageId); // this.author = notBlank(author); // this.text = notBlank(text); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/ImageComment.java // public class ImageComment { // public final String author; // public final String text; // // public ImageComment(final String author, final String text) { // this.author = author; // this.text = text; // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/ImagePost.java // public class ImagePost { // public final Long id; // public final String title; // public final Long numPoints; // public final Long numComments; // // public ImagePost(final Long id, final String title, final Long points, final Long numComments) { // this.id = notNull(id); // this.title = notBlank(title); // this.numPoints = notNull(points); // this.numComments = notNull(numComments); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/ImageUpload.java // public class ImageUpload { // public final String title; // public final byte[] data; // // public ImageUpload(final String title, final byte[] data) { // this.title = notBlank(title); // this.data = notNull(data); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/security/AuthenticatedUser.java // public class AuthenticatedUser { // public final String userName; // // public AuthenticatedUser(final String userName) { // this.userName = notBlank(userName); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/Image.java // public class Image { // public final byte[] data; // // public Image(final byte[] data) { // this.data = notNull(data); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/Title.java // public class Title { // private static final int MAN_LENGTH = 100; // // public final String value; // // public Title(final String value) { // this.value = notBlank(value); // isTrue(this.value.length() < MAN_LENGTH, "Title can be maximum 100 characters"); // } // }
import static java.util.stream.Collectors.toList; import static org.apache.commons.lang3.Validate.notBlank; import static org.apache.commons.lang3.Validate.notNull; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.context.SecurityContextHolder; import se.omegapoint.facepalm.application.ImageService; import se.omegapoint.facepalm.application.transfer.NewImageComment; import se.omegapoint.facepalm.client.config.Adapter; import se.omegapoint.facepalm.client.models.ImageComment; import se.omegapoint.facepalm.client.models.ImagePost; import se.omegapoint.facepalm.client.models.ImageUpload; import se.omegapoint.facepalm.client.security.AuthenticatedUser; import se.omegapoint.facepalm.domain.Image; import se.omegapoint.facepalm.domain.Title; import java.util.List; import java.util.Optional;
/* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.client.adapters; @Adapter public class ImageAdapter { private final ImageService imageService; @Autowired public ImageAdapter(final ImageService imageService) { this.imageService = notNull(imageService); } public List<ImagePost> getTopImagePosts() { return imageService.getTopImages().stream() .map(this::imagePost) .collect(toList()); } public Optional<ImagePost> getImage(final String id) { notBlank(id); return imageService.getImagePost(id).map(this::imagePost); }
// Path: src/main/java/se/omegapoint/facepalm/application/ImageService.java // @Service // public class ImageService { // // @Autowired // private ImageRepository imageRepository; // // @Autowired // private CommentRepository commentRepository; // // public List<ImagePost> getTopImages() { // return imageRepository.findAll(); // } // // public Optional<ImagePost> getImagePost(final String id) { // notBlank(id); // // return imageRepository.findById(id); // } // // public List<ImageComment> getCommentsForImage(final Long id) { // notNull(id); // // return commentRepository.findByImageId(id).stream().collect(toList()); // } // // public void addComment(final NewImageComment newImageComment) { // notNull(newImageComment); // // commentRepository.addComment(newImageComment.imageId, newImageComment.author, newImageComment.text); // } // // public void addImagePost(final Title title, final byte[] data) { // notNull(title); // notNull(data); // imageRepository.addImagePost(title, data); // } // // public Image getImageFor(final Long id) { // notNull(id); // return imageRepository.findImageByPostId(id); // } // } // // Path: src/main/java/se/omegapoint/facepalm/application/transfer/NewImageComment.java // public class NewImageComment { // public final Long imageId; // public final String author; // public final String text; // // public NewImageComment(final Long imageId, final String author, final String text) { // this.imageId = notNull(imageId); // this.author = notBlank(author); // this.text = notBlank(text); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/ImageComment.java // public class ImageComment { // public final String author; // public final String text; // // public ImageComment(final String author, final String text) { // this.author = author; // this.text = text; // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/ImagePost.java // public class ImagePost { // public final Long id; // public final String title; // public final Long numPoints; // public final Long numComments; // // public ImagePost(final Long id, final String title, final Long points, final Long numComments) { // this.id = notNull(id); // this.title = notBlank(title); // this.numPoints = notNull(points); // this.numComments = notNull(numComments); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/ImageUpload.java // public class ImageUpload { // public final String title; // public final byte[] data; // // public ImageUpload(final String title, final byte[] data) { // this.title = notBlank(title); // this.data = notNull(data); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/security/AuthenticatedUser.java // public class AuthenticatedUser { // public final String userName; // // public AuthenticatedUser(final String userName) { // this.userName = notBlank(userName); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/Image.java // public class Image { // public final byte[] data; // // public Image(final byte[] data) { // this.data = notNull(data); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/Title.java // public class Title { // private static final int MAN_LENGTH = 100; // // public final String value; // // public Title(final String value) { // this.value = notBlank(value); // isTrue(this.value.length() < MAN_LENGTH, "Title can be maximum 100 characters"); // } // } // Path: src/main/java/se/omegapoint/facepalm/client/adapters/ImageAdapter.java import static java.util.stream.Collectors.toList; import static org.apache.commons.lang3.Validate.notBlank; import static org.apache.commons.lang3.Validate.notNull; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.context.SecurityContextHolder; import se.omegapoint.facepalm.application.ImageService; import se.omegapoint.facepalm.application.transfer.NewImageComment; import se.omegapoint.facepalm.client.config.Adapter; import se.omegapoint.facepalm.client.models.ImageComment; import se.omegapoint.facepalm.client.models.ImagePost; import se.omegapoint.facepalm.client.models.ImageUpload; import se.omegapoint.facepalm.client.security.AuthenticatedUser; import se.omegapoint.facepalm.domain.Image; import se.omegapoint.facepalm.domain.Title; import java.util.List; import java.util.Optional; /* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.client.adapters; @Adapter public class ImageAdapter { private final ImageService imageService; @Autowired public ImageAdapter(final ImageService imageService) { this.imageService = notNull(imageService); } public List<ImagePost> getTopImagePosts() { return imageService.getTopImages().stream() .map(this::imagePost) .collect(toList()); } public Optional<ImagePost> getImage(final String id) { notBlank(id); return imageService.getImagePost(id).map(this::imagePost); }
public List<ImageComment> getCommentsForImage(final Long imageId) {
Omegapoint/facepalm
src/main/java/se/omegapoint/facepalm/client/adapters/ImageAdapter.java
// Path: src/main/java/se/omegapoint/facepalm/application/ImageService.java // @Service // public class ImageService { // // @Autowired // private ImageRepository imageRepository; // // @Autowired // private CommentRepository commentRepository; // // public List<ImagePost> getTopImages() { // return imageRepository.findAll(); // } // // public Optional<ImagePost> getImagePost(final String id) { // notBlank(id); // // return imageRepository.findById(id); // } // // public List<ImageComment> getCommentsForImage(final Long id) { // notNull(id); // // return commentRepository.findByImageId(id).stream().collect(toList()); // } // // public void addComment(final NewImageComment newImageComment) { // notNull(newImageComment); // // commentRepository.addComment(newImageComment.imageId, newImageComment.author, newImageComment.text); // } // // public void addImagePost(final Title title, final byte[] data) { // notNull(title); // notNull(data); // imageRepository.addImagePost(title, data); // } // // public Image getImageFor(final Long id) { // notNull(id); // return imageRepository.findImageByPostId(id); // } // } // // Path: src/main/java/se/omegapoint/facepalm/application/transfer/NewImageComment.java // public class NewImageComment { // public final Long imageId; // public final String author; // public final String text; // // public NewImageComment(final Long imageId, final String author, final String text) { // this.imageId = notNull(imageId); // this.author = notBlank(author); // this.text = notBlank(text); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/ImageComment.java // public class ImageComment { // public final String author; // public final String text; // // public ImageComment(final String author, final String text) { // this.author = author; // this.text = text; // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/ImagePost.java // public class ImagePost { // public final Long id; // public final String title; // public final Long numPoints; // public final Long numComments; // // public ImagePost(final Long id, final String title, final Long points, final Long numComments) { // this.id = notNull(id); // this.title = notBlank(title); // this.numPoints = notNull(points); // this.numComments = notNull(numComments); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/ImageUpload.java // public class ImageUpload { // public final String title; // public final byte[] data; // // public ImageUpload(final String title, final byte[] data) { // this.title = notBlank(title); // this.data = notNull(data); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/security/AuthenticatedUser.java // public class AuthenticatedUser { // public final String userName; // // public AuthenticatedUser(final String userName) { // this.userName = notBlank(userName); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/Image.java // public class Image { // public final byte[] data; // // public Image(final byte[] data) { // this.data = notNull(data); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/Title.java // public class Title { // private static final int MAN_LENGTH = 100; // // public final String value; // // public Title(final String value) { // this.value = notBlank(value); // isTrue(this.value.length() < MAN_LENGTH, "Title can be maximum 100 characters"); // } // }
import static java.util.stream.Collectors.toList; import static org.apache.commons.lang3.Validate.notBlank; import static org.apache.commons.lang3.Validate.notNull; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.context.SecurityContextHolder; import se.omegapoint.facepalm.application.ImageService; import se.omegapoint.facepalm.application.transfer.NewImageComment; import se.omegapoint.facepalm.client.config.Adapter; import se.omegapoint.facepalm.client.models.ImageComment; import se.omegapoint.facepalm.client.models.ImagePost; import se.omegapoint.facepalm.client.models.ImageUpload; import se.omegapoint.facepalm.client.security.AuthenticatedUser; import se.omegapoint.facepalm.domain.Image; import se.omegapoint.facepalm.domain.Title; import java.util.List; import java.util.Optional;
/* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.client.adapters; @Adapter public class ImageAdapter { private final ImageService imageService; @Autowired public ImageAdapter(final ImageService imageService) { this.imageService = notNull(imageService); } public List<ImagePost> getTopImagePosts() { return imageService.getTopImages().stream() .map(this::imagePost) .collect(toList()); } public Optional<ImagePost> getImage(final String id) { notBlank(id); return imageService.getImagePost(id).map(this::imagePost); } public List<ImageComment> getCommentsForImage(final Long imageId) { notNull(imageId); return imageService.getCommentsForImage(imageId).stream() .map(c -> new ImageComment(c.author, c.text)) .collect(toList()); } public void addComment(final String imageId, final String text) { notBlank(imageId); notBlank(text);
// Path: src/main/java/se/omegapoint/facepalm/application/ImageService.java // @Service // public class ImageService { // // @Autowired // private ImageRepository imageRepository; // // @Autowired // private CommentRepository commentRepository; // // public List<ImagePost> getTopImages() { // return imageRepository.findAll(); // } // // public Optional<ImagePost> getImagePost(final String id) { // notBlank(id); // // return imageRepository.findById(id); // } // // public List<ImageComment> getCommentsForImage(final Long id) { // notNull(id); // // return commentRepository.findByImageId(id).stream().collect(toList()); // } // // public void addComment(final NewImageComment newImageComment) { // notNull(newImageComment); // // commentRepository.addComment(newImageComment.imageId, newImageComment.author, newImageComment.text); // } // // public void addImagePost(final Title title, final byte[] data) { // notNull(title); // notNull(data); // imageRepository.addImagePost(title, data); // } // // public Image getImageFor(final Long id) { // notNull(id); // return imageRepository.findImageByPostId(id); // } // } // // Path: src/main/java/se/omegapoint/facepalm/application/transfer/NewImageComment.java // public class NewImageComment { // public final Long imageId; // public final String author; // public final String text; // // public NewImageComment(final Long imageId, final String author, final String text) { // this.imageId = notNull(imageId); // this.author = notBlank(author); // this.text = notBlank(text); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/ImageComment.java // public class ImageComment { // public final String author; // public final String text; // // public ImageComment(final String author, final String text) { // this.author = author; // this.text = text; // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/ImagePost.java // public class ImagePost { // public final Long id; // public final String title; // public final Long numPoints; // public final Long numComments; // // public ImagePost(final Long id, final String title, final Long points, final Long numComments) { // this.id = notNull(id); // this.title = notBlank(title); // this.numPoints = notNull(points); // this.numComments = notNull(numComments); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/ImageUpload.java // public class ImageUpload { // public final String title; // public final byte[] data; // // public ImageUpload(final String title, final byte[] data) { // this.title = notBlank(title); // this.data = notNull(data); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/security/AuthenticatedUser.java // public class AuthenticatedUser { // public final String userName; // // public AuthenticatedUser(final String userName) { // this.userName = notBlank(userName); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/Image.java // public class Image { // public final byte[] data; // // public Image(final byte[] data) { // this.data = notNull(data); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/Title.java // public class Title { // private static final int MAN_LENGTH = 100; // // public final String value; // // public Title(final String value) { // this.value = notBlank(value); // isTrue(this.value.length() < MAN_LENGTH, "Title can be maximum 100 characters"); // } // } // Path: src/main/java/se/omegapoint/facepalm/client/adapters/ImageAdapter.java import static java.util.stream.Collectors.toList; import static org.apache.commons.lang3.Validate.notBlank; import static org.apache.commons.lang3.Validate.notNull; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.context.SecurityContextHolder; import se.omegapoint.facepalm.application.ImageService; import se.omegapoint.facepalm.application.transfer.NewImageComment; import se.omegapoint.facepalm.client.config.Adapter; import se.omegapoint.facepalm.client.models.ImageComment; import se.omegapoint.facepalm.client.models.ImagePost; import se.omegapoint.facepalm.client.models.ImageUpload; import se.omegapoint.facepalm.client.security.AuthenticatedUser; import se.omegapoint.facepalm.domain.Image; import se.omegapoint.facepalm.domain.Title; import java.util.List; import java.util.Optional; /* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.client.adapters; @Adapter public class ImageAdapter { private final ImageService imageService; @Autowired public ImageAdapter(final ImageService imageService) { this.imageService = notNull(imageService); } public List<ImagePost> getTopImagePosts() { return imageService.getTopImages().stream() .map(this::imagePost) .collect(toList()); } public Optional<ImagePost> getImage(final String id) { notBlank(id); return imageService.getImagePost(id).map(this::imagePost); } public List<ImageComment> getCommentsForImage(final Long imageId) { notNull(imageId); return imageService.getCommentsForImage(imageId).stream() .map(c -> new ImageComment(c.author, c.text)) .collect(toList()); } public void addComment(final String imageId, final String text) { notBlank(imageId); notBlank(text);
imageService.addComment(new NewImageComment(Long.valueOf(imageId), currentUser(), text));
Omegapoint/facepalm
src/main/java/se/omegapoint/facepalm/client/adapters/ImageAdapter.java
// Path: src/main/java/se/omegapoint/facepalm/application/ImageService.java // @Service // public class ImageService { // // @Autowired // private ImageRepository imageRepository; // // @Autowired // private CommentRepository commentRepository; // // public List<ImagePost> getTopImages() { // return imageRepository.findAll(); // } // // public Optional<ImagePost> getImagePost(final String id) { // notBlank(id); // // return imageRepository.findById(id); // } // // public List<ImageComment> getCommentsForImage(final Long id) { // notNull(id); // // return commentRepository.findByImageId(id).stream().collect(toList()); // } // // public void addComment(final NewImageComment newImageComment) { // notNull(newImageComment); // // commentRepository.addComment(newImageComment.imageId, newImageComment.author, newImageComment.text); // } // // public void addImagePost(final Title title, final byte[] data) { // notNull(title); // notNull(data); // imageRepository.addImagePost(title, data); // } // // public Image getImageFor(final Long id) { // notNull(id); // return imageRepository.findImageByPostId(id); // } // } // // Path: src/main/java/se/omegapoint/facepalm/application/transfer/NewImageComment.java // public class NewImageComment { // public final Long imageId; // public final String author; // public final String text; // // public NewImageComment(final Long imageId, final String author, final String text) { // this.imageId = notNull(imageId); // this.author = notBlank(author); // this.text = notBlank(text); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/ImageComment.java // public class ImageComment { // public final String author; // public final String text; // // public ImageComment(final String author, final String text) { // this.author = author; // this.text = text; // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/ImagePost.java // public class ImagePost { // public final Long id; // public final String title; // public final Long numPoints; // public final Long numComments; // // public ImagePost(final Long id, final String title, final Long points, final Long numComments) { // this.id = notNull(id); // this.title = notBlank(title); // this.numPoints = notNull(points); // this.numComments = notNull(numComments); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/ImageUpload.java // public class ImageUpload { // public final String title; // public final byte[] data; // // public ImageUpload(final String title, final byte[] data) { // this.title = notBlank(title); // this.data = notNull(data); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/security/AuthenticatedUser.java // public class AuthenticatedUser { // public final String userName; // // public AuthenticatedUser(final String userName) { // this.userName = notBlank(userName); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/Image.java // public class Image { // public final byte[] data; // // public Image(final byte[] data) { // this.data = notNull(data); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/Title.java // public class Title { // private static final int MAN_LENGTH = 100; // // public final String value; // // public Title(final String value) { // this.value = notBlank(value); // isTrue(this.value.length() < MAN_LENGTH, "Title can be maximum 100 characters"); // } // }
import static java.util.stream.Collectors.toList; import static org.apache.commons.lang3.Validate.notBlank; import static org.apache.commons.lang3.Validate.notNull; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.context.SecurityContextHolder; import se.omegapoint.facepalm.application.ImageService; import se.omegapoint.facepalm.application.transfer.NewImageComment; import se.omegapoint.facepalm.client.config.Adapter; import se.omegapoint.facepalm.client.models.ImageComment; import se.omegapoint.facepalm.client.models.ImagePost; import se.omegapoint.facepalm.client.models.ImageUpload; import se.omegapoint.facepalm.client.security.AuthenticatedUser; import se.omegapoint.facepalm.domain.Image; import se.omegapoint.facepalm.domain.Title; import java.util.List; import java.util.Optional;
.map(this::imagePost) .collect(toList()); } public Optional<ImagePost> getImage(final String id) { notBlank(id); return imageService.getImagePost(id).map(this::imagePost); } public List<ImageComment> getCommentsForImage(final Long imageId) { notNull(imageId); return imageService.getCommentsForImage(imageId).stream() .map(c -> new ImageComment(c.author, c.text)) .collect(toList()); } public void addComment(final String imageId, final String text) { notBlank(imageId); notBlank(text); imageService.addComment(new NewImageComment(Long.valueOf(imageId), currentUser(), text)); } public void addImage(final ImageUpload imageUpload) { notNull(imageUpload); imageService.addImagePost(new Title(imageUpload.title), imageUpload.data); }
// Path: src/main/java/se/omegapoint/facepalm/application/ImageService.java // @Service // public class ImageService { // // @Autowired // private ImageRepository imageRepository; // // @Autowired // private CommentRepository commentRepository; // // public List<ImagePost> getTopImages() { // return imageRepository.findAll(); // } // // public Optional<ImagePost> getImagePost(final String id) { // notBlank(id); // // return imageRepository.findById(id); // } // // public List<ImageComment> getCommentsForImage(final Long id) { // notNull(id); // // return commentRepository.findByImageId(id).stream().collect(toList()); // } // // public void addComment(final NewImageComment newImageComment) { // notNull(newImageComment); // // commentRepository.addComment(newImageComment.imageId, newImageComment.author, newImageComment.text); // } // // public void addImagePost(final Title title, final byte[] data) { // notNull(title); // notNull(data); // imageRepository.addImagePost(title, data); // } // // public Image getImageFor(final Long id) { // notNull(id); // return imageRepository.findImageByPostId(id); // } // } // // Path: src/main/java/se/omegapoint/facepalm/application/transfer/NewImageComment.java // public class NewImageComment { // public final Long imageId; // public final String author; // public final String text; // // public NewImageComment(final Long imageId, final String author, final String text) { // this.imageId = notNull(imageId); // this.author = notBlank(author); // this.text = notBlank(text); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/ImageComment.java // public class ImageComment { // public final String author; // public final String text; // // public ImageComment(final String author, final String text) { // this.author = author; // this.text = text; // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/ImagePost.java // public class ImagePost { // public final Long id; // public final String title; // public final Long numPoints; // public final Long numComments; // // public ImagePost(final Long id, final String title, final Long points, final Long numComments) { // this.id = notNull(id); // this.title = notBlank(title); // this.numPoints = notNull(points); // this.numComments = notNull(numComments); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/ImageUpload.java // public class ImageUpload { // public final String title; // public final byte[] data; // // public ImageUpload(final String title, final byte[] data) { // this.title = notBlank(title); // this.data = notNull(data); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/security/AuthenticatedUser.java // public class AuthenticatedUser { // public final String userName; // // public AuthenticatedUser(final String userName) { // this.userName = notBlank(userName); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/Image.java // public class Image { // public final byte[] data; // // public Image(final byte[] data) { // this.data = notNull(data); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/Title.java // public class Title { // private static final int MAN_LENGTH = 100; // // public final String value; // // public Title(final String value) { // this.value = notBlank(value); // isTrue(this.value.length() < MAN_LENGTH, "Title can be maximum 100 characters"); // } // } // Path: src/main/java/se/omegapoint/facepalm/client/adapters/ImageAdapter.java import static java.util.stream.Collectors.toList; import static org.apache.commons.lang3.Validate.notBlank; import static org.apache.commons.lang3.Validate.notNull; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.context.SecurityContextHolder; import se.omegapoint.facepalm.application.ImageService; import se.omegapoint.facepalm.application.transfer.NewImageComment; import se.omegapoint.facepalm.client.config.Adapter; import se.omegapoint.facepalm.client.models.ImageComment; import se.omegapoint.facepalm.client.models.ImagePost; import se.omegapoint.facepalm.client.models.ImageUpload; import se.omegapoint.facepalm.client.security.AuthenticatedUser; import se.omegapoint.facepalm.domain.Image; import se.omegapoint.facepalm.domain.Title; import java.util.List; import java.util.Optional; .map(this::imagePost) .collect(toList()); } public Optional<ImagePost> getImage(final String id) { notBlank(id); return imageService.getImagePost(id).map(this::imagePost); } public List<ImageComment> getCommentsForImage(final Long imageId) { notNull(imageId); return imageService.getCommentsForImage(imageId).stream() .map(c -> new ImageComment(c.author, c.text)) .collect(toList()); } public void addComment(final String imageId, final String text) { notBlank(imageId); notBlank(text); imageService.addComment(new NewImageComment(Long.valueOf(imageId), currentUser(), text)); } public void addImage(final ImageUpload imageUpload) { notNull(imageUpload); imageService.addImagePost(new Title(imageUpload.title), imageUpload.data); }
public Image fetchImage(final Long id) {
Omegapoint/facepalm
src/main/java/se/omegapoint/facepalm/client/adapters/ImageAdapter.java
// Path: src/main/java/se/omegapoint/facepalm/application/ImageService.java // @Service // public class ImageService { // // @Autowired // private ImageRepository imageRepository; // // @Autowired // private CommentRepository commentRepository; // // public List<ImagePost> getTopImages() { // return imageRepository.findAll(); // } // // public Optional<ImagePost> getImagePost(final String id) { // notBlank(id); // // return imageRepository.findById(id); // } // // public List<ImageComment> getCommentsForImage(final Long id) { // notNull(id); // // return commentRepository.findByImageId(id).stream().collect(toList()); // } // // public void addComment(final NewImageComment newImageComment) { // notNull(newImageComment); // // commentRepository.addComment(newImageComment.imageId, newImageComment.author, newImageComment.text); // } // // public void addImagePost(final Title title, final byte[] data) { // notNull(title); // notNull(data); // imageRepository.addImagePost(title, data); // } // // public Image getImageFor(final Long id) { // notNull(id); // return imageRepository.findImageByPostId(id); // } // } // // Path: src/main/java/se/omegapoint/facepalm/application/transfer/NewImageComment.java // public class NewImageComment { // public final Long imageId; // public final String author; // public final String text; // // public NewImageComment(final Long imageId, final String author, final String text) { // this.imageId = notNull(imageId); // this.author = notBlank(author); // this.text = notBlank(text); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/ImageComment.java // public class ImageComment { // public final String author; // public final String text; // // public ImageComment(final String author, final String text) { // this.author = author; // this.text = text; // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/ImagePost.java // public class ImagePost { // public final Long id; // public final String title; // public final Long numPoints; // public final Long numComments; // // public ImagePost(final Long id, final String title, final Long points, final Long numComments) { // this.id = notNull(id); // this.title = notBlank(title); // this.numPoints = notNull(points); // this.numComments = notNull(numComments); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/ImageUpload.java // public class ImageUpload { // public final String title; // public final byte[] data; // // public ImageUpload(final String title, final byte[] data) { // this.title = notBlank(title); // this.data = notNull(data); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/security/AuthenticatedUser.java // public class AuthenticatedUser { // public final String userName; // // public AuthenticatedUser(final String userName) { // this.userName = notBlank(userName); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/Image.java // public class Image { // public final byte[] data; // // public Image(final byte[] data) { // this.data = notNull(data); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/Title.java // public class Title { // private static final int MAN_LENGTH = 100; // // public final String value; // // public Title(final String value) { // this.value = notBlank(value); // isTrue(this.value.length() < MAN_LENGTH, "Title can be maximum 100 characters"); // } // }
import static java.util.stream.Collectors.toList; import static org.apache.commons.lang3.Validate.notBlank; import static org.apache.commons.lang3.Validate.notNull; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.context.SecurityContextHolder; import se.omegapoint.facepalm.application.ImageService; import se.omegapoint.facepalm.application.transfer.NewImageComment; import se.omegapoint.facepalm.client.config.Adapter; import se.omegapoint.facepalm.client.models.ImageComment; import se.omegapoint.facepalm.client.models.ImagePost; import se.omegapoint.facepalm.client.models.ImageUpload; import se.omegapoint.facepalm.client.security.AuthenticatedUser; import se.omegapoint.facepalm.domain.Image; import se.omegapoint.facepalm.domain.Title; import java.util.List; import java.util.Optional;
return imageService.getImagePost(id).map(this::imagePost); } public List<ImageComment> getCommentsForImage(final Long imageId) { notNull(imageId); return imageService.getCommentsForImage(imageId).stream() .map(c -> new ImageComment(c.author, c.text)) .collect(toList()); } public void addComment(final String imageId, final String text) { notBlank(imageId); notBlank(text); imageService.addComment(new NewImageComment(Long.valueOf(imageId), currentUser(), text)); } public void addImage(final ImageUpload imageUpload) { notNull(imageUpload); imageService.addImagePost(new Title(imageUpload.title), imageUpload.data); } public Image fetchImage(final Long id) { notNull(id); return imageService.getImageFor(id); } public String currentUser() {
// Path: src/main/java/se/omegapoint/facepalm/application/ImageService.java // @Service // public class ImageService { // // @Autowired // private ImageRepository imageRepository; // // @Autowired // private CommentRepository commentRepository; // // public List<ImagePost> getTopImages() { // return imageRepository.findAll(); // } // // public Optional<ImagePost> getImagePost(final String id) { // notBlank(id); // // return imageRepository.findById(id); // } // // public List<ImageComment> getCommentsForImage(final Long id) { // notNull(id); // // return commentRepository.findByImageId(id).stream().collect(toList()); // } // // public void addComment(final NewImageComment newImageComment) { // notNull(newImageComment); // // commentRepository.addComment(newImageComment.imageId, newImageComment.author, newImageComment.text); // } // // public void addImagePost(final Title title, final byte[] data) { // notNull(title); // notNull(data); // imageRepository.addImagePost(title, data); // } // // public Image getImageFor(final Long id) { // notNull(id); // return imageRepository.findImageByPostId(id); // } // } // // Path: src/main/java/se/omegapoint/facepalm/application/transfer/NewImageComment.java // public class NewImageComment { // public final Long imageId; // public final String author; // public final String text; // // public NewImageComment(final Long imageId, final String author, final String text) { // this.imageId = notNull(imageId); // this.author = notBlank(author); // this.text = notBlank(text); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/ImageComment.java // public class ImageComment { // public final String author; // public final String text; // // public ImageComment(final String author, final String text) { // this.author = author; // this.text = text; // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/ImagePost.java // public class ImagePost { // public final Long id; // public final String title; // public final Long numPoints; // public final Long numComments; // // public ImagePost(final Long id, final String title, final Long points, final Long numComments) { // this.id = notNull(id); // this.title = notBlank(title); // this.numPoints = notNull(points); // this.numComments = notNull(numComments); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/ImageUpload.java // public class ImageUpload { // public final String title; // public final byte[] data; // // public ImageUpload(final String title, final byte[] data) { // this.title = notBlank(title); // this.data = notNull(data); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/security/AuthenticatedUser.java // public class AuthenticatedUser { // public final String userName; // // public AuthenticatedUser(final String userName) { // this.userName = notBlank(userName); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/Image.java // public class Image { // public final byte[] data; // // public Image(final byte[] data) { // this.data = notNull(data); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/Title.java // public class Title { // private static final int MAN_LENGTH = 100; // // public final String value; // // public Title(final String value) { // this.value = notBlank(value); // isTrue(this.value.length() < MAN_LENGTH, "Title can be maximum 100 characters"); // } // } // Path: src/main/java/se/omegapoint/facepalm/client/adapters/ImageAdapter.java import static java.util.stream.Collectors.toList; import static org.apache.commons.lang3.Validate.notBlank; import static org.apache.commons.lang3.Validate.notNull; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.context.SecurityContextHolder; import se.omegapoint.facepalm.application.ImageService; import se.omegapoint.facepalm.application.transfer.NewImageComment; import se.omegapoint.facepalm.client.config.Adapter; import se.omegapoint.facepalm.client.models.ImageComment; import se.omegapoint.facepalm.client.models.ImagePost; import se.omegapoint.facepalm.client.models.ImageUpload; import se.omegapoint.facepalm.client.security.AuthenticatedUser; import se.omegapoint.facepalm.domain.Image; import se.omegapoint.facepalm.domain.Title; import java.util.List; import java.util.Optional; return imageService.getImagePost(id).map(this::imagePost); } public List<ImageComment> getCommentsForImage(final Long imageId) { notNull(imageId); return imageService.getCommentsForImage(imageId).stream() .map(c -> new ImageComment(c.author, c.text)) .collect(toList()); } public void addComment(final String imageId, final String text) { notBlank(imageId); notBlank(text); imageService.addComment(new NewImageComment(Long.valueOf(imageId), currentUser(), text)); } public void addImage(final ImageUpload imageUpload) { notNull(imageUpload); imageService.addImagePost(new Title(imageUpload.title), imageUpload.data); } public Image fetchImage(final Long id) { notNull(id); return imageService.getImageFor(id); } public String currentUser() {
final AuthenticatedUser authenticatedUser = (AuthenticatedUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
Omegapoint/facepalm
src/main/java/se/omegapoint/facepalm/client/models/User.java
// Path: src/main/java/se/omegapoint/facepalm/client/security/AuthenticatedUser.java // public class AuthenticatedUser { // public final String userName; // // public AuthenticatedUser(final String userName) { // this.userName = notBlank(userName); // } // }
import se.omegapoint.facepalm.client.security.AuthenticatedUser; import static org.apache.commons.lang3.Validate.notNull;
/* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.client.models; public class User { public final String username;
// Path: src/main/java/se/omegapoint/facepalm/client/security/AuthenticatedUser.java // public class AuthenticatedUser { // public final String userName; // // public AuthenticatedUser(final String userName) { // this.userName = notBlank(userName); // } // } // Path: src/main/java/se/omegapoint/facepalm/client/models/User.java import se.omegapoint.facepalm.client.security.AuthenticatedUser; import static org.apache.commons.lang3.Validate.notNull; /* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.client.models; public class User { public final String username;
public User(final AuthenticatedUser authenticatedUser) {
Omegapoint/facepalm
src/main/java/se/omegapoint/facepalm/client/security/DbAuthenticationProvider.java
// Path: src/main/java/se/omegapoint/facepalm/domain/User.java // public class User { // public final String username; // public final String email; // public final String firstname; // public final String lastname; // // /* // Is there a better way than just using strings I wonder? // */ // public User(final String username, final String email, final String firstname, final String lastname) { // this.username = notBlank(username); // this.email = notBlank(email); // this.firstname = notBlank(firstname); // this.lastname = notBlank(lastname); // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // final User user = (User) o; // return Objects.equals(username, user.username) && // Objects.equals(email, user.email) && // Objects.equals(firstname, user.firstname) && // Objects.equals(lastname, user.lastname); // } // // @Override // public int hashCode() { // return Objects.hash(username, email, firstname, lastname); // } // // @Override // public String toString() { // return "User{" + // "username='" + username + '\'' + // ", email='" + email + '\'' + // ", firstname='" + firstname + '\'' + // ", lastname='" + lastname + '\'' + // '}'; // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/repository/UserRepository.java // public interface UserRepository { // Optional<User> findByUsername(final String username); // // Set<User> findFriendsFor(String username); // // Optional<User> findByNameAndPassword(final String username, final String password); // // List<User> findLike(String value); // // void addFriend(String user, String friend); // // void addUser(NewUserCredentials credentials); // // boolean usersAreFriends(String userA, String userB); // }
import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import se.omegapoint.facepalm.domain.User; import se.omegapoint.facepalm.domain.repository.UserRepository; import java.util.Optional; import static java.util.Collections.emptyList; import static org.apache.commons.lang3.Validate.notNull;
/* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.client.security; public class DbAuthenticationProvider implements AuthenticationProvider { private final UserRepository userRepository; public DbAuthenticationProvider(final UserRepository userRepository) { this.userRepository = notNull(userRepository); } @Override public Authentication authenticate(final Authentication authentication) throws AuthenticationException { final UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication; final String username = (String) token.getPrincipal(); final String password = (String) token.getCredentials();
// Path: src/main/java/se/omegapoint/facepalm/domain/User.java // public class User { // public final String username; // public final String email; // public final String firstname; // public final String lastname; // // /* // Is there a better way than just using strings I wonder? // */ // public User(final String username, final String email, final String firstname, final String lastname) { // this.username = notBlank(username); // this.email = notBlank(email); // this.firstname = notBlank(firstname); // this.lastname = notBlank(lastname); // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // final User user = (User) o; // return Objects.equals(username, user.username) && // Objects.equals(email, user.email) && // Objects.equals(firstname, user.firstname) && // Objects.equals(lastname, user.lastname); // } // // @Override // public int hashCode() { // return Objects.hash(username, email, firstname, lastname); // } // // @Override // public String toString() { // return "User{" + // "username='" + username + '\'' + // ", email='" + email + '\'' + // ", firstname='" + firstname + '\'' + // ", lastname='" + lastname + '\'' + // '}'; // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/repository/UserRepository.java // public interface UserRepository { // Optional<User> findByUsername(final String username); // // Set<User> findFriendsFor(String username); // // Optional<User> findByNameAndPassword(final String username, final String password); // // List<User> findLike(String value); // // void addFriend(String user, String friend); // // void addUser(NewUserCredentials credentials); // // boolean usersAreFriends(String userA, String userB); // } // Path: src/main/java/se/omegapoint/facepalm/client/security/DbAuthenticationProvider.java import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import se.omegapoint.facepalm.domain.User; import se.omegapoint.facepalm.domain.repository.UserRepository; import java.util.Optional; import static java.util.Collections.emptyList; import static org.apache.commons.lang3.Validate.notNull; /* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.client.security; public class DbAuthenticationProvider implements AuthenticationProvider { private final UserRepository userRepository; public DbAuthenticationProvider(final UserRepository userRepository) { this.userRepository = notNull(userRepository); } @Override public Authentication authenticate(final Authentication authentication) throws AuthenticationException { final UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication; final String username = (String) token.getPrincipal(); final String password = (String) token.getCredentials();
final Optional<User> user = userRepository.findByNameAndPassword(username, password);
Omegapoint/facepalm
src/main/java/se/omegapoint/facepalm/infrastructure/event/ReactorEventService.java
// Path: src/main/java/se/omegapoint/facepalm/domain/event/ApplicationEvent.java // public interface ApplicationEvent { // String message(); // } // // Path: src/main/java/se/omegapoint/facepalm/domain/event/EventService.java // public interface EventService { // void publish(ApplicationEvent event); // }
import reactor.bus.Event; import reactor.bus.EventBus; import reactor.bus.selector.Selector; import reactor.fn.Consumer; import se.omegapoint.facepalm.domain.event.ApplicationEvent; import se.omegapoint.facepalm.domain.event.EventService; import static org.apache.commons.lang3.Validate.notNull; import static se.omegapoint.facepalm.infrastructure.event.EventChannel.GLOBAL;
/* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.infrastructure.event; public class ReactorEventService implements EventService { private final EventBus eventBus; public ReactorEventService(final EventBus eventBus) { this.eventBus = notNull(eventBus); }
// Path: src/main/java/se/omegapoint/facepalm/domain/event/ApplicationEvent.java // public interface ApplicationEvent { // String message(); // } // // Path: src/main/java/se/omegapoint/facepalm/domain/event/EventService.java // public interface EventService { // void publish(ApplicationEvent event); // } // Path: src/main/java/se/omegapoint/facepalm/infrastructure/event/ReactorEventService.java import reactor.bus.Event; import reactor.bus.EventBus; import reactor.bus.selector.Selector; import reactor.fn.Consumer; import se.omegapoint.facepalm.domain.event.ApplicationEvent; import se.omegapoint.facepalm.domain.event.EventService; import static org.apache.commons.lang3.Validate.notNull; import static se.omegapoint.facepalm.infrastructure.event.EventChannel.GLOBAL; /* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.infrastructure.event; public class ReactorEventService implements EventService { private final EventBus eventBus; public ReactorEventService(final EventBus eventBus) { this.eventBus = notNull(eventBus); }
public void publish(final ApplicationEvent event) {
Omegapoint/facepalm
src/main/java/se/omegapoint/facepalm/client/controllers/SearchController.java
// Path: src/main/java/se/omegapoint/facepalm/client/adapters/SearchAdapter.java // @Adapter // public class SearchAdapter { // // private final UserService userService; // private final FriendService friendService; // // @Autowired // public SearchAdapter(final UserService userService, final FriendService friendService) { // this.userService = notNull(userService); // this.friendService = notNull(friendService); // } // // public List<SearchResultEntry> findUsersLike(final SearchQuery searchQuery) { // notNull(searchQuery); // // return userService.searchForUsersLike(searchQuery.value) // .stream() // .filter(u -> !u.username.equals(currentUser().userName)) // .map(u -> new SearchResultEntry(u.username, u.email, u.firstname, u.lastname, isFriendsWithCurrentUser(u))) // .collect(toList()); // } // // private boolean isFriendsWithCurrentUser(final User friend) { // return friendService.usersAreFriends(currentUser().userName, friend.username); // } // // private AuthenticatedUser currentUser() { // return (AuthenticatedUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/SearchQuery.java // public class SearchQuery { // // public final String value; // // public SearchQuery(final String value) { // this.value = value; // } // }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import se.omegapoint.facepalm.client.adapters.SearchAdapter; import se.omegapoint.facepalm.client.models.SearchQuery; import static java.util.Collections.emptyList; import static org.apache.commons.lang3.StringUtils.isNotBlank; import static org.apache.commons.lang3.Validate.notNull;
/* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.client.controllers; @Controller public class SearchController {
// Path: src/main/java/se/omegapoint/facepalm/client/adapters/SearchAdapter.java // @Adapter // public class SearchAdapter { // // private final UserService userService; // private final FriendService friendService; // // @Autowired // public SearchAdapter(final UserService userService, final FriendService friendService) { // this.userService = notNull(userService); // this.friendService = notNull(friendService); // } // // public List<SearchResultEntry> findUsersLike(final SearchQuery searchQuery) { // notNull(searchQuery); // // return userService.searchForUsersLike(searchQuery.value) // .stream() // .filter(u -> !u.username.equals(currentUser().userName)) // .map(u -> new SearchResultEntry(u.username, u.email, u.firstname, u.lastname, isFriendsWithCurrentUser(u))) // .collect(toList()); // } // // private boolean isFriendsWithCurrentUser(final User friend) { // return friendService.usersAreFriends(currentUser().userName, friend.username); // } // // private AuthenticatedUser currentUser() { // return (AuthenticatedUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/SearchQuery.java // public class SearchQuery { // // public final String value; // // public SearchQuery(final String value) { // this.value = value; // } // } // Path: src/main/java/se/omegapoint/facepalm/client/controllers/SearchController.java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import se.omegapoint.facepalm.client.adapters.SearchAdapter; import se.omegapoint.facepalm.client.models.SearchQuery; import static java.util.Collections.emptyList; import static org.apache.commons.lang3.StringUtils.isNotBlank; import static org.apache.commons.lang3.Validate.notNull; /* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.client.controllers; @Controller public class SearchController {
private final SearchAdapter searchAdapter;
Omegapoint/facepalm
src/main/java/se/omegapoint/facepalm/client/controllers/SearchController.java
// Path: src/main/java/se/omegapoint/facepalm/client/adapters/SearchAdapter.java // @Adapter // public class SearchAdapter { // // private final UserService userService; // private final FriendService friendService; // // @Autowired // public SearchAdapter(final UserService userService, final FriendService friendService) { // this.userService = notNull(userService); // this.friendService = notNull(friendService); // } // // public List<SearchResultEntry> findUsersLike(final SearchQuery searchQuery) { // notNull(searchQuery); // // return userService.searchForUsersLike(searchQuery.value) // .stream() // .filter(u -> !u.username.equals(currentUser().userName)) // .map(u -> new SearchResultEntry(u.username, u.email, u.firstname, u.lastname, isFriendsWithCurrentUser(u))) // .collect(toList()); // } // // private boolean isFriendsWithCurrentUser(final User friend) { // return friendService.usersAreFriends(currentUser().userName, friend.username); // } // // private AuthenticatedUser currentUser() { // return (AuthenticatedUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/SearchQuery.java // public class SearchQuery { // // public final String value; // // public SearchQuery(final String value) { // this.value = value; // } // }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import se.omegapoint.facepalm.client.adapters.SearchAdapter; import se.omegapoint.facepalm.client.models.SearchQuery; import static java.util.Collections.emptyList; import static org.apache.commons.lang3.StringUtils.isNotBlank; import static org.apache.commons.lang3.Validate.notNull;
/* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.client.controllers; @Controller public class SearchController { private final SearchAdapter searchAdapter; @Autowired public SearchController(final SearchAdapter searchAdapter) { this.searchAdapter = notNull(searchAdapter); } @RequestMapping(value = "search", method = RequestMethod.GET)
// Path: src/main/java/se/omegapoint/facepalm/client/adapters/SearchAdapter.java // @Adapter // public class SearchAdapter { // // private final UserService userService; // private final FriendService friendService; // // @Autowired // public SearchAdapter(final UserService userService, final FriendService friendService) { // this.userService = notNull(userService); // this.friendService = notNull(friendService); // } // // public List<SearchResultEntry> findUsersLike(final SearchQuery searchQuery) { // notNull(searchQuery); // // return userService.searchForUsersLike(searchQuery.value) // .stream() // .filter(u -> !u.username.equals(currentUser().userName)) // .map(u -> new SearchResultEntry(u.username, u.email, u.firstname, u.lastname, isFriendsWithCurrentUser(u))) // .collect(toList()); // } // // private boolean isFriendsWithCurrentUser(final User friend) { // return friendService.usersAreFriends(currentUser().userName, friend.username); // } // // private AuthenticatedUser currentUser() { // return (AuthenticatedUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/SearchQuery.java // public class SearchQuery { // // public final String value; // // public SearchQuery(final String value) { // this.value = value; // } // } // Path: src/main/java/se/omegapoint/facepalm/client/controllers/SearchController.java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import se.omegapoint.facepalm.client.adapters.SearchAdapter; import se.omegapoint.facepalm.client.models.SearchQuery; import static java.util.Collections.emptyList; import static org.apache.commons.lang3.StringUtils.isNotBlank; import static org.apache.commons.lang3.Validate.notNull; /* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.client.controllers; @Controller public class SearchController { private final SearchAdapter searchAdapter; @Autowired public SearchController(final SearchAdapter searchAdapter) { this.searchAdapter = notNull(searchAdapter); } @RequestMapping(value = "search", method = RequestMethod.GET)
public String search(final @RequestParam(value = "query", required = false) SearchQuery searchQuery, final Model model) {
Omegapoint/facepalm
src/main/java/se/omegapoint/facepalm/client/config/ControllerConfig.java
// Path: src/main/java/se/omegapoint/facepalm/application/CommercialService.java // @Service // public class CommercialService { // // public List<Commercial> getCommercials() { // return ImmutableList.of(new Commercial("Red dead redemption", "images/commercials/reddead.jpg")); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/User.java // public class User { // public final String username; // // public User(final AuthenticatedUser authenticatedUser) { // notNull(authenticatedUser); // this.username = authenticatedUser.userName; // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/security/AuthenticatedUser.java // public class AuthenticatedUser { // public final String userName; // // public AuthenticatedUser(final String userName) { // this.userName = notBlank(userName); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/Commercial.java // public class Commercial { // public final String title; // public final String uri; // // public Commercial(String title, String uri) { // this.title = title; // this.uri = uri; // } // }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ModelAttribute; import se.omegapoint.facepalm.application.CommercialService; import se.omegapoint.facepalm.client.models.User; import se.omegapoint.facepalm.client.security.AuthenticatedUser; import se.omegapoint.facepalm.domain.Commercial; import java.util.List;
/* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.client.config; @ControllerAdvice public class ControllerConfig { @Autowired
// Path: src/main/java/se/omegapoint/facepalm/application/CommercialService.java // @Service // public class CommercialService { // // public List<Commercial> getCommercials() { // return ImmutableList.of(new Commercial("Red dead redemption", "images/commercials/reddead.jpg")); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/User.java // public class User { // public final String username; // // public User(final AuthenticatedUser authenticatedUser) { // notNull(authenticatedUser); // this.username = authenticatedUser.userName; // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/security/AuthenticatedUser.java // public class AuthenticatedUser { // public final String userName; // // public AuthenticatedUser(final String userName) { // this.userName = notBlank(userName); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/Commercial.java // public class Commercial { // public final String title; // public final String uri; // // public Commercial(String title, String uri) { // this.title = title; // this.uri = uri; // } // } // Path: src/main/java/se/omegapoint/facepalm/client/config/ControllerConfig.java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ModelAttribute; import se.omegapoint.facepalm.application.CommercialService; import se.omegapoint.facepalm.client.models.User; import se.omegapoint.facepalm.client.security.AuthenticatedUser; import se.omegapoint.facepalm.domain.Commercial; import java.util.List; /* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.client.config; @ControllerAdvice public class ControllerConfig { @Autowired
CommercialService commercialService;
Omegapoint/facepalm
src/main/java/se/omegapoint/facepalm/client/config/ControllerConfig.java
// Path: src/main/java/se/omegapoint/facepalm/application/CommercialService.java // @Service // public class CommercialService { // // public List<Commercial> getCommercials() { // return ImmutableList.of(new Commercial("Red dead redemption", "images/commercials/reddead.jpg")); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/User.java // public class User { // public final String username; // // public User(final AuthenticatedUser authenticatedUser) { // notNull(authenticatedUser); // this.username = authenticatedUser.userName; // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/security/AuthenticatedUser.java // public class AuthenticatedUser { // public final String userName; // // public AuthenticatedUser(final String userName) { // this.userName = notBlank(userName); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/Commercial.java // public class Commercial { // public final String title; // public final String uri; // // public Commercial(String title, String uri) { // this.title = title; // this.uri = uri; // } // }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ModelAttribute; import se.omegapoint.facepalm.application.CommercialService; import se.omegapoint.facepalm.client.models.User; import se.omegapoint.facepalm.client.security.AuthenticatedUser; import se.omegapoint.facepalm.domain.Commercial; import java.util.List;
/* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.client.config; @ControllerAdvice public class ControllerConfig { @Autowired CommercialService commercialService; @ModelAttribute("user")
// Path: src/main/java/se/omegapoint/facepalm/application/CommercialService.java // @Service // public class CommercialService { // // public List<Commercial> getCommercials() { // return ImmutableList.of(new Commercial("Red dead redemption", "images/commercials/reddead.jpg")); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/User.java // public class User { // public final String username; // // public User(final AuthenticatedUser authenticatedUser) { // notNull(authenticatedUser); // this.username = authenticatedUser.userName; // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/security/AuthenticatedUser.java // public class AuthenticatedUser { // public final String userName; // // public AuthenticatedUser(final String userName) { // this.userName = notBlank(userName); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/Commercial.java // public class Commercial { // public final String title; // public final String uri; // // public Commercial(String title, String uri) { // this.title = title; // this.uri = uri; // } // } // Path: src/main/java/se/omegapoint/facepalm/client/config/ControllerConfig.java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ModelAttribute; import se.omegapoint.facepalm.application.CommercialService; import se.omegapoint.facepalm.client.models.User; import se.omegapoint.facepalm.client.security.AuthenticatedUser; import se.omegapoint.facepalm.domain.Commercial; import java.util.List; /* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.client.config; @ControllerAdvice public class ControllerConfig { @Autowired CommercialService commercialService; @ModelAttribute("user")
public User user() {
Omegapoint/facepalm
src/main/java/se/omegapoint/facepalm/client/config/ControllerConfig.java
// Path: src/main/java/se/omegapoint/facepalm/application/CommercialService.java // @Service // public class CommercialService { // // public List<Commercial> getCommercials() { // return ImmutableList.of(new Commercial("Red dead redemption", "images/commercials/reddead.jpg")); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/User.java // public class User { // public final String username; // // public User(final AuthenticatedUser authenticatedUser) { // notNull(authenticatedUser); // this.username = authenticatedUser.userName; // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/security/AuthenticatedUser.java // public class AuthenticatedUser { // public final String userName; // // public AuthenticatedUser(final String userName) { // this.userName = notBlank(userName); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/Commercial.java // public class Commercial { // public final String title; // public final String uri; // // public Commercial(String title, String uri) { // this.title = title; // this.uri = uri; // } // }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ModelAttribute; import se.omegapoint.facepalm.application.CommercialService; import se.omegapoint.facepalm.client.models.User; import se.omegapoint.facepalm.client.security.AuthenticatedUser; import se.omegapoint.facepalm.domain.Commercial; import java.util.List;
/* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.client.config; @ControllerAdvice public class ControllerConfig { @Autowired CommercialService commercialService; @ModelAttribute("user") public User user() { if (SecurityContextHolder.getContext().getAuthentication() instanceof UsernamePasswordAuthenticationToken) {
// Path: src/main/java/se/omegapoint/facepalm/application/CommercialService.java // @Service // public class CommercialService { // // public List<Commercial> getCommercials() { // return ImmutableList.of(new Commercial("Red dead redemption", "images/commercials/reddead.jpg")); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/User.java // public class User { // public final String username; // // public User(final AuthenticatedUser authenticatedUser) { // notNull(authenticatedUser); // this.username = authenticatedUser.userName; // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/security/AuthenticatedUser.java // public class AuthenticatedUser { // public final String userName; // // public AuthenticatedUser(final String userName) { // this.userName = notBlank(userName); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/Commercial.java // public class Commercial { // public final String title; // public final String uri; // // public Commercial(String title, String uri) { // this.title = title; // this.uri = uri; // } // } // Path: src/main/java/se/omegapoint/facepalm/client/config/ControllerConfig.java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ModelAttribute; import se.omegapoint.facepalm.application.CommercialService; import se.omegapoint.facepalm.client.models.User; import se.omegapoint.facepalm.client.security.AuthenticatedUser; import se.omegapoint.facepalm.domain.Commercial; import java.util.List; /* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.client.config; @ControllerAdvice public class ControllerConfig { @Autowired CommercialService commercialService; @ModelAttribute("user") public User user() { if (SecurityContextHolder.getContext().getAuthentication() instanceof UsernamePasswordAuthenticationToken) {
final AuthenticatedUser authenticatedUser = (AuthenticatedUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
Omegapoint/facepalm
src/main/java/se/omegapoint/facepalm/client/config/ControllerConfig.java
// Path: src/main/java/se/omegapoint/facepalm/application/CommercialService.java // @Service // public class CommercialService { // // public List<Commercial> getCommercials() { // return ImmutableList.of(new Commercial("Red dead redemption", "images/commercials/reddead.jpg")); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/User.java // public class User { // public final String username; // // public User(final AuthenticatedUser authenticatedUser) { // notNull(authenticatedUser); // this.username = authenticatedUser.userName; // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/security/AuthenticatedUser.java // public class AuthenticatedUser { // public final String userName; // // public AuthenticatedUser(final String userName) { // this.userName = notBlank(userName); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/Commercial.java // public class Commercial { // public final String title; // public final String uri; // // public Commercial(String title, String uri) { // this.title = title; // this.uri = uri; // } // }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ModelAttribute; import se.omegapoint.facepalm.application.CommercialService; import se.omegapoint.facepalm.client.models.User; import se.omegapoint.facepalm.client.security.AuthenticatedUser; import se.omegapoint.facepalm.domain.Commercial; import java.util.List;
/* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.client.config; @ControllerAdvice public class ControllerConfig { @Autowired CommercialService commercialService; @ModelAttribute("user") public User user() { if (SecurityContextHolder.getContext().getAuthentication() instanceof UsernamePasswordAuthenticationToken) { final AuthenticatedUser authenticatedUser = (AuthenticatedUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); return new User(authenticatedUser); } return null; } @ModelAttribute("commercials")
// Path: src/main/java/se/omegapoint/facepalm/application/CommercialService.java // @Service // public class CommercialService { // // public List<Commercial> getCommercials() { // return ImmutableList.of(new Commercial("Red dead redemption", "images/commercials/reddead.jpg")); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/User.java // public class User { // public final String username; // // public User(final AuthenticatedUser authenticatedUser) { // notNull(authenticatedUser); // this.username = authenticatedUser.userName; // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/security/AuthenticatedUser.java // public class AuthenticatedUser { // public final String userName; // // public AuthenticatedUser(final String userName) { // this.userName = notBlank(userName); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/Commercial.java // public class Commercial { // public final String title; // public final String uri; // // public Commercial(String title, String uri) { // this.title = title; // this.uri = uri; // } // } // Path: src/main/java/se/omegapoint/facepalm/client/config/ControllerConfig.java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ModelAttribute; import se.omegapoint.facepalm.application.CommercialService; import se.omegapoint.facepalm.client.models.User; import se.omegapoint.facepalm.client.security.AuthenticatedUser; import se.omegapoint.facepalm.domain.Commercial; import java.util.List; /* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.client.config; @ControllerAdvice public class ControllerConfig { @Autowired CommercialService commercialService; @ModelAttribute("user") public User user() { if (SecurityContextHolder.getContext().getAuthentication() instanceof UsernamePasswordAuthenticationToken) { final AuthenticatedUser authenticatedUser = (AuthenticatedUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); return new User(authenticatedUser); } return null; } @ModelAttribute("commercials")
public List<Commercial> commercials() {
Omegapoint/facepalm
src/main/java/se/omegapoint/facepalm/application/FriendService.java
// Path: src/main/java/se/omegapoint/facepalm/domain/User.java // public class User { // public final String username; // public final String email; // public final String firstname; // public final String lastname; // // /* // Is there a better way than just using strings I wonder? // */ // public User(final String username, final String email, final String firstname, final String lastname) { // this.username = notBlank(username); // this.email = notBlank(email); // this.firstname = notBlank(firstname); // this.lastname = notBlank(lastname); // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // final User user = (User) o; // return Objects.equals(username, user.username) && // Objects.equals(email, user.email) && // Objects.equals(firstname, user.firstname) && // Objects.equals(lastname, user.lastname); // } // // @Override // public int hashCode() { // return Objects.hash(username, email, firstname, lastname); // } // // @Override // public String toString() { // return "User{" + // "username='" + username + '\'' + // ", email='" + email + '\'' + // ", firstname='" + firstname + '\'' + // ", lastname='" + lastname + '\'' + // '}'; // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/repository/UserRepository.java // public interface UserRepository { // Optional<User> findByUsername(final String username); // // Set<User> findFriendsFor(String username); // // Optional<User> findByNameAndPassword(final String username, final String password); // // List<User> findLike(String value); // // void addFriend(String user, String friend); // // void addUser(NewUserCredentials credentials); // // boolean usersAreFriends(String userA, String userB); // }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import se.omegapoint.facepalm.domain.User; import se.omegapoint.facepalm.domain.repository.UserRepository; import java.util.Optional; import java.util.Set; import static org.apache.commons.lang3.Validate.notBlank; import static org.apache.commons.lang3.Validate.notNull;
/* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.application; @Service public class FriendService {
// Path: src/main/java/se/omegapoint/facepalm/domain/User.java // public class User { // public final String username; // public final String email; // public final String firstname; // public final String lastname; // // /* // Is there a better way than just using strings I wonder? // */ // public User(final String username, final String email, final String firstname, final String lastname) { // this.username = notBlank(username); // this.email = notBlank(email); // this.firstname = notBlank(firstname); // this.lastname = notBlank(lastname); // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // final User user = (User) o; // return Objects.equals(username, user.username) && // Objects.equals(email, user.email) && // Objects.equals(firstname, user.firstname) && // Objects.equals(lastname, user.lastname); // } // // @Override // public int hashCode() { // return Objects.hash(username, email, firstname, lastname); // } // // @Override // public String toString() { // return "User{" + // "username='" + username + '\'' + // ", email='" + email + '\'' + // ", firstname='" + firstname + '\'' + // ", lastname='" + lastname + '\'' + // '}'; // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/repository/UserRepository.java // public interface UserRepository { // Optional<User> findByUsername(final String username); // // Set<User> findFriendsFor(String username); // // Optional<User> findByNameAndPassword(final String username, final String password); // // List<User> findLike(String value); // // void addFriend(String user, String friend); // // void addUser(NewUserCredentials credentials); // // boolean usersAreFriends(String userA, String userB); // } // Path: src/main/java/se/omegapoint/facepalm/application/FriendService.java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import se.omegapoint.facepalm.domain.User; import se.omegapoint.facepalm.domain.repository.UserRepository; import java.util.Optional; import java.util.Set; import static org.apache.commons.lang3.Validate.notBlank; import static org.apache.commons.lang3.Validate.notNull; /* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.application; @Service public class FriendService {
private final UserRepository userRepository;
Omegapoint/facepalm
src/main/java/se/omegapoint/facepalm/application/FriendService.java
// Path: src/main/java/se/omegapoint/facepalm/domain/User.java // public class User { // public final String username; // public final String email; // public final String firstname; // public final String lastname; // // /* // Is there a better way than just using strings I wonder? // */ // public User(final String username, final String email, final String firstname, final String lastname) { // this.username = notBlank(username); // this.email = notBlank(email); // this.firstname = notBlank(firstname); // this.lastname = notBlank(lastname); // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // final User user = (User) o; // return Objects.equals(username, user.username) && // Objects.equals(email, user.email) && // Objects.equals(firstname, user.firstname) && // Objects.equals(lastname, user.lastname); // } // // @Override // public int hashCode() { // return Objects.hash(username, email, firstname, lastname); // } // // @Override // public String toString() { // return "User{" + // "username='" + username + '\'' + // ", email='" + email + '\'' + // ", firstname='" + firstname + '\'' + // ", lastname='" + lastname + '\'' + // '}'; // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/repository/UserRepository.java // public interface UserRepository { // Optional<User> findByUsername(final String username); // // Set<User> findFriendsFor(String username); // // Optional<User> findByNameAndPassword(final String username, final String password); // // List<User> findLike(String value); // // void addFriend(String user, String friend); // // void addUser(NewUserCredentials credentials); // // boolean usersAreFriends(String userA, String userB); // }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import se.omegapoint.facepalm.domain.User; import se.omegapoint.facepalm.domain.repository.UserRepository; import java.util.Optional; import java.util.Set; import static org.apache.commons.lang3.Validate.notBlank; import static org.apache.commons.lang3.Validate.notNull;
/* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.application; @Service public class FriendService { private final UserRepository userRepository; @Autowired public FriendService(final UserRepository userRepository) { this.userRepository = notNull(userRepository); }
// Path: src/main/java/se/omegapoint/facepalm/domain/User.java // public class User { // public final String username; // public final String email; // public final String firstname; // public final String lastname; // // /* // Is there a better way than just using strings I wonder? // */ // public User(final String username, final String email, final String firstname, final String lastname) { // this.username = notBlank(username); // this.email = notBlank(email); // this.firstname = notBlank(firstname); // this.lastname = notBlank(lastname); // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // final User user = (User) o; // return Objects.equals(username, user.username) && // Objects.equals(email, user.email) && // Objects.equals(firstname, user.firstname) && // Objects.equals(lastname, user.lastname); // } // // @Override // public int hashCode() { // return Objects.hash(username, email, firstname, lastname); // } // // @Override // public String toString() { // return "User{" + // "username='" + username + '\'' + // ", email='" + email + '\'' + // ", firstname='" + firstname + '\'' + // ", lastname='" + lastname + '\'' + // '}'; // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/repository/UserRepository.java // public interface UserRepository { // Optional<User> findByUsername(final String username); // // Set<User> findFriendsFor(String username); // // Optional<User> findByNameAndPassword(final String username, final String password); // // List<User> findLike(String value); // // void addFriend(String user, String friend); // // void addUser(NewUserCredentials credentials); // // boolean usersAreFriends(String userA, String userB); // } // Path: src/main/java/se/omegapoint/facepalm/application/FriendService.java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import se.omegapoint.facepalm.domain.User; import se.omegapoint.facepalm.domain.repository.UserRepository; import java.util.Optional; import java.util.Set; import static org.apache.commons.lang3.Validate.notBlank; import static org.apache.commons.lang3.Validate.notNull; /* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.application; @Service public class FriendService { private final UserRepository userRepository; @Autowired public FriendService(final UserRepository userRepository) { this.userRepository = notNull(userRepository); }
public Set<User> friendFor(final String username) {
Omegapoint/facepalm
src/main/java/se/omegapoint/facepalm/client/controllers/ImageController.java
// Path: src/main/java/se/omegapoint/facepalm/client/adapters/ImageAdapter.java // @Adapter // public class ImageAdapter { // // private final ImageService imageService; // // @Autowired // public ImageAdapter(final ImageService imageService) { // this.imageService = notNull(imageService); // } // // // public List<ImagePost> getTopImagePosts() { // return imageService.getTopImages().stream() // .map(this::imagePost) // .collect(toList()); // } // // public Optional<ImagePost> getImage(final String id) { // notBlank(id); // // return imageService.getImagePost(id).map(this::imagePost); // } // // public List<ImageComment> getCommentsForImage(final Long imageId) { // notNull(imageId); // // return imageService.getCommentsForImage(imageId).stream() // .map(c -> new ImageComment(c.author, c.text)) // .collect(toList()); // } // // public void addComment(final String imageId, final String text) { // notBlank(imageId); // notBlank(text); // // imageService.addComment(new NewImageComment(Long.valueOf(imageId), currentUser(), text)); // } // // public void addImage(final ImageUpload imageUpload) { // notNull(imageUpload); // imageService.addImagePost(new Title(imageUpload.title), imageUpload.data); // } // // public Image fetchImage(final Long id) { // notNull(id); // return imageService.getImageFor(id); // } // // public String currentUser() { // final AuthenticatedUser authenticatedUser = (AuthenticatedUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); // return authenticatedUser.userName; // } // // private ImagePost imagePost(final se.omegapoint.facepalm.domain.ImagePost image) { // return new ImagePost(image.id, image.title.value, image.numPoints.value, image.numComments.value); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/ImageComment.java // public class ImageComment { // public final String author; // public final String text; // // public ImageComment(final String author, final String text) { // this.author = author; // this.text = text; // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/ImagePost.java // public class ImagePost { // public final Long id; // public final String title; // public final Long numPoints; // public final Long numComments; // // public ImagePost(final Long id, final String title, final Long points, final Long numComments) { // this.id = notNull(id); // this.title = notBlank(title); // this.numPoints = notNull(points); // this.numComments = notNull(numComments); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/ImageUpload.java // public class ImageUpload { // public final String title; // public final byte[] data; // // public ImageUpload(final String title, final byte[] data) { // this.title = notBlank(title); // this.data = notNull(data); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/Image.java // public class Image { // public final byte[] data; // // public Image(final byte[] data) { // this.data = notNull(data); // } // }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import se.omegapoint.facepalm.client.adapters.ImageAdapter; import se.omegapoint.facepalm.client.models.ImageComment; import se.omegapoint.facepalm.client.models.ImagePost; import se.omegapoint.facepalm.client.models.ImageUpload; import se.omegapoint.facepalm.domain.Image; import java.io.IOException; import java.util.List; import java.util.Optional; import static org.apache.commons.lang3.Validate.notNull;
/* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.client.controllers; @Controller public class ImageController { @Autowired
// Path: src/main/java/se/omegapoint/facepalm/client/adapters/ImageAdapter.java // @Adapter // public class ImageAdapter { // // private final ImageService imageService; // // @Autowired // public ImageAdapter(final ImageService imageService) { // this.imageService = notNull(imageService); // } // // // public List<ImagePost> getTopImagePosts() { // return imageService.getTopImages().stream() // .map(this::imagePost) // .collect(toList()); // } // // public Optional<ImagePost> getImage(final String id) { // notBlank(id); // // return imageService.getImagePost(id).map(this::imagePost); // } // // public List<ImageComment> getCommentsForImage(final Long imageId) { // notNull(imageId); // // return imageService.getCommentsForImage(imageId).stream() // .map(c -> new ImageComment(c.author, c.text)) // .collect(toList()); // } // // public void addComment(final String imageId, final String text) { // notBlank(imageId); // notBlank(text); // // imageService.addComment(new NewImageComment(Long.valueOf(imageId), currentUser(), text)); // } // // public void addImage(final ImageUpload imageUpload) { // notNull(imageUpload); // imageService.addImagePost(new Title(imageUpload.title), imageUpload.data); // } // // public Image fetchImage(final Long id) { // notNull(id); // return imageService.getImageFor(id); // } // // public String currentUser() { // final AuthenticatedUser authenticatedUser = (AuthenticatedUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); // return authenticatedUser.userName; // } // // private ImagePost imagePost(final se.omegapoint.facepalm.domain.ImagePost image) { // return new ImagePost(image.id, image.title.value, image.numPoints.value, image.numComments.value); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/ImageComment.java // public class ImageComment { // public final String author; // public final String text; // // public ImageComment(final String author, final String text) { // this.author = author; // this.text = text; // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/ImagePost.java // public class ImagePost { // public final Long id; // public final String title; // public final Long numPoints; // public final Long numComments; // // public ImagePost(final Long id, final String title, final Long points, final Long numComments) { // this.id = notNull(id); // this.title = notBlank(title); // this.numPoints = notNull(points); // this.numComments = notNull(numComments); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/ImageUpload.java // public class ImageUpload { // public final String title; // public final byte[] data; // // public ImageUpload(final String title, final byte[] data) { // this.title = notBlank(title); // this.data = notNull(data); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/Image.java // public class Image { // public final byte[] data; // // public Image(final byte[] data) { // this.data = notNull(data); // } // } // Path: src/main/java/se/omegapoint/facepalm/client/controllers/ImageController.java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import se.omegapoint.facepalm.client.adapters.ImageAdapter; import se.omegapoint.facepalm.client.models.ImageComment; import se.omegapoint.facepalm.client.models.ImagePost; import se.omegapoint.facepalm.client.models.ImageUpload; import se.omegapoint.facepalm.domain.Image; import java.io.IOException; import java.util.List; import java.util.Optional; import static org.apache.commons.lang3.Validate.notNull; /* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.client.controllers; @Controller public class ImageController { @Autowired
private ImageAdapter imageAdapter;
Omegapoint/facepalm
src/main/java/se/omegapoint/facepalm/client/controllers/ImageController.java
// Path: src/main/java/se/omegapoint/facepalm/client/adapters/ImageAdapter.java // @Adapter // public class ImageAdapter { // // private final ImageService imageService; // // @Autowired // public ImageAdapter(final ImageService imageService) { // this.imageService = notNull(imageService); // } // // // public List<ImagePost> getTopImagePosts() { // return imageService.getTopImages().stream() // .map(this::imagePost) // .collect(toList()); // } // // public Optional<ImagePost> getImage(final String id) { // notBlank(id); // // return imageService.getImagePost(id).map(this::imagePost); // } // // public List<ImageComment> getCommentsForImage(final Long imageId) { // notNull(imageId); // // return imageService.getCommentsForImage(imageId).stream() // .map(c -> new ImageComment(c.author, c.text)) // .collect(toList()); // } // // public void addComment(final String imageId, final String text) { // notBlank(imageId); // notBlank(text); // // imageService.addComment(new NewImageComment(Long.valueOf(imageId), currentUser(), text)); // } // // public void addImage(final ImageUpload imageUpload) { // notNull(imageUpload); // imageService.addImagePost(new Title(imageUpload.title), imageUpload.data); // } // // public Image fetchImage(final Long id) { // notNull(id); // return imageService.getImageFor(id); // } // // public String currentUser() { // final AuthenticatedUser authenticatedUser = (AuthenticatedUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); // return authenticatedUser.userName; // } // // private ImagePost imagePost(final se.omegapoint.facepalm.domain.ImagePost image) { // return new ImagePost(image.id, image.title.value, image.numPoints.value, image.numComments.value); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/ImageComment.java // public class ImageComment { // public final String author; // public final String text; // // public ImageComment(final String author, final String text) { // this.author = author; // this.text = text; // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/ImagePost.java // public class ImagePost { // public final Long id; // public final String title; // public final Long numPoints; // public final Long numComments; // // public ImagePost(final Long id, final String title, final Long points, final Long numComments) { // this.id = notNull(id); // this.title = notBlank(title); // this.numPoints = notNull(points); // this.numComments = notNull(numComments); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/ImageUpload.java // public class ImageUpload { // public final String title; // public final byte[] data; // // public ImageUpload(final String title, final byte[] data) { // this.title = notBlank(title); // this.data = notNull(data); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/Image.java // public class Image { // public final byte[] data; // // public Image(final byte[] data) { // this.data = notNull(data); // } // }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import se.omegapoint.facepalm.client.adapters.ImageAdapter; import se.omegapoint.facepalm.client.models.ImageComment; import se.omegapoint.facepalm.client.models.ImagePost; import se.omegapoint.facepalm.client.models.ImageUpload; import se.omegapoint.facepalm.domain.Image; import java.io.IOException; import java.util.List; import java.util.Optional; import static org.apache.commons.lang3.Validate.notNull;
/* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.client.controllers; @Controller public class ImageController { @Autowired private ImageAdapter imageAdapter; @RequestMapping("/") public String index(final Model model) { model.addAttribute("posts", imageAdapter.getTopImagePosts()); return "index"; } @RequestMapping("/image") public String image(final @RequestParam String id, final Model model) {
// Path: src/main/java/se/omegapoint/facepalm/client/adapters/ImageAdapter.java // @Adapter // public class ImageAdapter { // // private final ImageService imageService; // // @Autowired // public ImageAdapter(final ImageService imageService) { // this.imageService = notNull(imageService); // } // // // public List<ImagePost> getTopImagePosts() { // return imageService.getTopImages().stream() // .map(this::imagePost) // .collect(toList()); // } // // public Optional<ImagePost> getImage(final String id) { // notBlank(id); // // return imageService.getImagePost(id).map(this::imagePost); // } // // public List<ImageComment> getCommentsForImage(final Long imageId) { // notNull(imageId); // // return imageService.getCommentsForImage(imageId).stream() // .map(c -> new ImageComment(c.author, c.text)) // .collect(toList()); // } // // public void addComment(final String imageId, final String text) { // notBlank(imageId); // notBlank(text); // // imageService.addComment(new NewImageComment(Long.valueOf(imageId), currentUser(), text)); // } // // public void addImage(final ImageUpload imageUpload) { // notNull(imageUpload); // imageService.addImagePost(new Title(imageUpload.title), imageUpload.data); // } // // public Image fetchImage(final Long id) { // notNull(id); // return imageService.getImageFor(id); // } // // public String currentUser() { // final AuthenticatedUser authenticatedUser = (AuthenticatedUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); // return authenticatedUser.userName; // } // // private ImagePost imagePost(final se.omegapoint.facepalm.domain.ImagePost image) { // return new ImagePost(image.id, image.title.value, image.numPoints.value, image.numComments.value); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/ImageComment.java // public class ImageComment { // public final String author; // public final String text; // // public ImageComment(final String author, final String text) { // this.author = author; // this.text = text; // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/ImagePost.java // public class ImagePost { // public final Long id; // public final String title; // public final Long numPoints; // public final Long numComments; // // public ImagePost(final Long id, final String title, final Long points, final Long numComments) { // this.id = notNull(id); // this.title = notBlank(title); // this.numPoints = notNull(points); // this.numComments = notNull(numComments); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/ImageUpload.java // public class ImageUpload { // public final String title; // public final byte[] data; // // public ImageUpload(final String title, final byte[] data) { // this.title = notBlank(title); // this.data = notNull(data); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/Image.java // public class Image { // public final byte[] data; // // public Image(final byte[] data) { // this.data = notNull(data); // } // } // Path: src/main/java/se/omegapoint/facepalm/client/controllers/ImageController.java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import se.omegapoint.facepalm.client.adapters.ImageAdapter; import se.omegapoint.facepalm.client.models.ImageComment; import se.omegapoint.facepalm.client.models.ImagePost; import se.omegapoint.facepalm.client.models.ImageUpload; import se.omegapoint.facepalm.domain.Image; import java.io.IOException; import java.util.List; import java.util.Optional; import static org.apache.commons.lang3.Validate.notNull; /* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.client.controllers; @Controller public class ImageController { @Autowired private ImageAdapter imageAdapter; @RequestMapping("/") public String index(final Model model) { model.addAttribute("posts", imageAdapter.getTopImagePosts()); return "index"; } @RequestMapping("/image") public String image(final @RequestParam String id, final Model model) {
final Optional<ImagePost> image = imageAdapter.getImage(id);
Omegapoint/facepalm
src/main/java/se/omegapoint/facepalm/client/controllers/ImageController.java
// Path: src/main/java/se/omegapoint/facepalm/client/adapters/ImageAdapter.java // @Adapter // public class ImageAdapter { // // private final ImageService imageService; // // @Autowired // public ImageAdapter(final ImageService imageService) { // this.imageService = notNull(imageService); // } // // // public List<ImagePost> getTopImagePosts() { // return imageService.getTopImages().stream() // .map(this::imagePost) // .collect(toList()); // } // // public Optional<ImagePost> getImage(final String id) { // notBlank(id); // // return imageService.getImagePost(id).map(this::imagePost); // } // // public List<ImageComment> getCommentsForImage(final Long imageId) { // notNull(imageId); // // return imageService.getCommentsForImage(imageId).stream() // .map(c -> new ImageComment(c.author, c.text)) // .collect(toList()); // } // // public void addComment(final String imageId, final String text) { // notBlank(imageId); // notBlank(text); // // imageService.addComment(new NewImageComment(Long.valueOf(imageId), currentUser(), text)); // } // // public void addImage(final ImageUpload imageUpload) { // notNull(imageUpload); // imageService.addImagePost(new Title(imageUpload.title), imageUpload.data); // } // // public Image fetchImage(final Long id) { // notNull(id); // return imageService.getImageFor(id); // } // // public String currentUser() { // final AuthenticatedUser authenticatedUser = (AuthenticatedUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); // return authenticatedUser.userName; // } // // private ImagePost imagePost(final se.omegapoint.facepalm.domain.ImagePost image) { // return new ImagePost(image.id, image.title.value, image.numPoints.value, image.numComments.value); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/ImageComment.java // public class ImageComment { // public final String author; // public final String text; // // public ImageComment(final String author, final String text) { // this.author = author; // this.text = text; // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/ImagePost.java // public class ImagePost { // public final Long id; // public final String title; // public final Long numPoints; // public final Long numComments; // // public ImagePost(final Long id, final String title, final Long points, final Long numComments) { // this.id = notNull(id); // this.title = notBlank(title); // this.numPoints = notNull(points); // this.numComments = notNull(numComments); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/ImageUpload.java // public class ImageUpload { // public final String title; // public final byte[] data; // // public ImageUpload(final String title, final byte[] data) { // this.title = notBlank(title); // this.data = notNull(data); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/Image.java // public class Image { // public final byte[] data; // // public Image(final byte[] data) { // this.data = notNull(data); // } // }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import se.omegapoint.facepalm.client.adapters.ImageAdapter; import se.omegapoint.facepalm.client.models.ImageComment; import se.omegapoint.facepalm.client.models.ImagePost; import se.omegapoint.facepalm.client.models.ImageUpload; import se.omegapoint.facepalm.domain.Image; import java.io.IOException; import java.util.List; import java.util.Optional; import static org.apache.commons.lang3.Validate.notNull;
/* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.client.controllers; @Controller public class ImageController { @Autowired private ImageAdapter imageAdapter; @RequestMapping("/") public String index(final Model model) { model.addAttribute("posts", imageAdapter.getTopImagePosts()); return "index"; } @RequestMapping("/image") public String image(final @RequestParam String id, final Model model) { final Optional<ImagePost> image = imageAdapter.getImage(id); if (!image.isPresent()) { return "redirect:/404"; }
// Path: src/main/java/se/omegapoint/facepalm/client/adapters/ImageAdapter.java // @Adapter // public class ImageAdapter { // // private final ImageService imageService; // // @Autowired // public ImageAdapter(final ImageService imageService) { // this.imageService = notNull(imageService); // } // // // public List<ImagePost> getTopImagePosts() { // return imageService.getTopImages().stream() // .map(this::imagePost) // .collect(toList()); // } // // public Optional<ImagePost> getImage(final String id) { // notBlank(id); // // return imageService.getImagePost(id).map(this::imagePost); // } // // public List<ImageComment> getCommentsForImage(final Long imageId) { // notNull(imageId); // // return imageService.getCommentsForImage(imageId).stream() // .map(c -> new ImageComment(c.author, c.text)) // .collect(toList()); // } // // public void addComment(final String imageId, final String text) { // notBlank(imageId); // notBlank(text); // // imageService.addComment(new NewImageComment(Long.valueOf(imageId), currentUser(), text)); // } // // public void addImage(final ImageUpload imageUpload) { // notNull(imageUpload); // imageService.addImagePost(new Title(imageUpload.title), imageUpload.data); // } // // public Image fetchImage(final Long id) { // notNull(id); // return imageService.getImageFor(id); // } // // public String currentUser() { // final AuthenticatedUser authenticatedUser = (AuthenticatedUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); // return authenticatedUser.userName; // } // // private ImagePost imagePost(final se.omegapoint.facepalm.domain.ImagePost image) { // return new ImagePost(image.id, image.title.value, image.numPoints.value, image.numComments.value); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/ImageComment.java // public class ImageComment { // public final String author; // public final String text; // // public ImageComment(final String author, final String text) { // this.author = author; // this.text = text; // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/ImagePost.java // public class ImagePost { // public final Long id; // public final String title; // public final Long numPoints; // public final Long numComments; // // public ImagePost(final Long id, final String title, final Long points, final Long numComments) { // this.id = notNull(id); // this.title = notBlank(title); // this.numPoints = notNull(points); // this.numComments = notNull(numComments); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/ImageUpload.java // public class ImageUpload { // public final String title; // public final byte[] data; // // public ImageUpload(final String title, final byte[] data) { // this.title = notBlank(title); // this.data = notNull(data); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/Image.java // public class Image { // public final byte[] data; // // public Image(final byte[] data) { // this.data = notNull(data); // } // } // Path: src/main/java/se/omegapoint/facepalm/client/controllers/ImageController.java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import se.omegapoint.facepalm.client.adapters.ImageAdapter; import se.omegapoint.facepalm.client.models.ImageComment; import se.omegapoint.facepalm.client.models.ImagePost; import se.omegapoint.facepalm.client.models.ImageUpload; import se.omegapoint.facepalm.domain.Image; import java.io.IOException; import java.util.List; import java.util.Optional; import static org.apache.commons.lang3.Validate.notNull; /* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.client.controllers; @Controller public class ImageController { @Autowired private ImageAdapter imageAdapter; @RequestMapping("/") public String index(final Model model) { model.addAttribute("posts", imageAdapter.getTopImagePosts()); return "index"; } @RequestMapping("/image") public String image(final @RequestParam String id, final Model model) { final Optional<ImagePost> image = imageAdapter.getImage(id); if (!image.isPresent()) { return "redirect:/404"; }
final List<ImageComment> comments = imageAdapter.getCommentsForImage(image.get().id);
Omegapoint/facepalm
src/main/java/se/omegapoint/facepalm/client/controllers/ImageController.java
// Path: src/main/java/se/omegapoint/facepalm/client/adapters/ImageAdapter.java // @Adapter // public class ImageAdapter { // // private final ImageService imageService; // // @Autowired // public ImageAdapter(final ImageService imageService) { // this.imageService = notNull(imageService); // } // // // public List<ImagePost> getTopImagePosts() { // return imageService.getTopImages().stream() // .map(this::imagePost) // .collect(toList()); // } // // public Optional<ImagePost> getImage(final String id) { // notBlank(id); // // return imageService.getImagePost(id).map(this::imagePost); // } // // public List<ImageComment> getCommentsForImage(final Long imageId) { // notNull(imageId); // // return imageService.getCommentsForImage(imageId).stream() // .map(c -> new ImageComment(c.author, c.text)) // .collect(toList()); // } // // public void addComment(final String imageId, final String text) { // notBlank(imageId); // notBlank(text); // // imageService.addComment(new NewImageComment(Long.valueOf(imageId), currentUser(), text)); // } // // public void addImage(final ImageUpload imageUpload) { // notNull(imageUpload); // imageService.addImagePost(new Title(imageUpload.title), imageUpload.data); // } // // public Image fetchImage(final Long id) { // notNull(id); // return imageService.getImageFor(id); // } // // public String currentUser() { // final AuthenticatedUser authenticatedUser = (AuthenticatedUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); // return authenticatedUser.userName; // } // // private ImagePost imagePost(final se.omegapoint.facepalm.domain.ImagePost image) { // return new ImagePost(image.id, image.title.value, image.numPoints.value, image.numComments.value); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/ImageComment.java // public class ImageComment { // public final String author; // public final String text; // // public ImageComment(final String author, final String text) { // this.author = author; // this.text = text; // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/ImagePost.java // public class ImagePost { // public final Long id; // public final String title; // public final Long numPoints; // public final Long numComments; // // public ImagePost(final Long id, final String title, final Long points, final Long numComments) { // this.id = notNull(id); // this.title = notBlank(title); // this.numPoints = notNull(points); // this.numComments = notNull(numComments); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/ImageUpload.java // public class ImageUpload { // public final String title; // public final byte[] data; // // public ImageUpload(final String title, final byte[] data) { // this.title = notBlank(title); // this.data = notNull(data); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/Image.java // public class Image { // public final byte[] data; // // public Image(final byte[] data) { // this.data = notNull(data); // } // }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import se.omegapoint.facepalm.client.adapters.ImageAdapter; import se.omegapoint.facepalm.client.models.ImageComment; import se.omegapoint.facepalm.client.models.ImagePost; import se.omegapoint.facepalm.client.models.ImageUpload; import se.omegapoint.facepalm.domain.Image; import java.io.IOException; import java.util.List; import java.util.Optional; import static org.apache.commons.lang3.Validate.notNull;
@RequestMapping("/") public String index(final Model model) { model.addAttribute("posts", imageAdapter.getTopImagePosts()); return "index"; } @RequestMapping("/image") public String image(final @RequestParam String id, final Model model) { final Optional<ImagePost> image = imageAdapter.getImage(id); if (!image.isPresent()) { return "redirect:/404"; } final List<ImageComment> comments = imageAdapter.getCommentsForImage(image.get().id); model.addAttribute("image", image.get()); model.addAttribute("comments", comments); return "image"; } @RequestMapping(value = "/comment", method = RequestMethod.POST) public String addComment(final @RequestParam("imageId") String imageId, final @RequestParam("text") String text) { imageAdapter.addComment(imageId, text); return "redirect:/image?id=" + imageId; } @RequestMapping(value = "/postImage", method = RequestMethod.POST) public String postImage(final @RequestParam("title") String title, final @RequestParam("file") MultipartFile file) { if (!file.isEmpty()) { try { final byte[] data = notNull(file.getBytes());
// Path: src/main/java/se/omegapoint/facepalm/client/adapters/ImageAdapter.java // @Adapter // public class ImageAdapter { // // private final ImageService imageService; // // @Autowired // public ImageAdapter(final ImageService imageService) { // this.imageService = notNull(imageService); // } // // // public List<ImagePost> getTopImagePosts() { // return imageService.getTopImages().stream() // .map(this::imagePost) // .collect(toList()); // } // // public Optional<ImagePost> getImage(final String id) { // notBlank(id); // // return imageService.getImagePost(id).map(this::imagePost); // } // // public List<ImageComment> getCommentsForImage(final Long imageId) { // notNull(imageId); // // return imageService.getCommentsForImage(imageId).stream() // .map(c -> new ImageComment(c.author, c.text)) // .collect(toList()); // } // // public void addComment(final String imageId, final String text) { // notBlank(imageId); // notBlank(text); // // imageService.addComment(new NewImageComment(Long.valueOf(imageId), currentUser(), text)); // } // // public void addImage(final ImageUpload imageUpload) { // notNull(imageUpload); // imageService.addImagePost(new Title(imageUpload.title), imageUpload.data); // } // // public Image fetchImage(final Long id) { // notNull(id); // return imageService.getImageFor(id); // } // // public String currentUser() { // final AuthenticatedUser authenticatedUser = (AuthenticatedUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); // return authenticatedUser.userName; // } // // private ImagePost imagePost(final se.omegapoint.facepalm.domain.ImagePost image) { // return new ImagePost(image.id, image.title.value, image.numPoints.value, image.numComments.value); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/ImageComment.java // public class ImageComment { // public final String author; // public final String text; // // public ImageComment(final String author, final String text) { // this.author = author; // this.text = text; // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/ImagePost.java // public class ImagePost { // public final Long id; // public final String title; // public final Long numPoints; // public final Long numComments; // // public ImagePost(final Long id, final String title, final Long points, final Long numComments) { // this.id = notNull(id); // this.title = notBlank(title); // this.numPoints = notNull(points); // this.numComments = notNull(numComments); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/ImageUpload.java // public class ImageUpload { // public final String title; // public final byte[] data; // // public ImageUpload(final String title, final byte[] data) { // this.title = notBlank(title); // this.data = notNull(data); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/Image.java // public class Image { // public final byte[] data; // // public Image(final byte[] data) { // this.data = notNull(data); // } // } // Path: src/main/java/se/omegapoint/facepalm/client/controllers/ImageController.java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import se.omegapoint.facepalm.client.adapters.ImageAdapter; import se.omegapoint.facepalm.client.models.ImageComment; import se.omegapoint.facepalm.client.models.ImagePost; import se.omegapoint.facepalm.client.models.ImageUpload; import se.omegapoint.facepalm.domain.Image; import java.io.IOException; import java.util.List; import java.util.Optional; import static org.apache.commons.lang3.Validate.notNull; @RequestMapping("/") public String index(final Model model) { model.addAttribute("posts", imageAdapter.getTopImagePosts()); return "index"; } @RequestMapping("/image") public String image(final @RequestParam String id, final Model model) { final Optional<ImagePost> image = imageAdapter.getImage(id); if (!image.isPresent()) { return "redirect:/404"; } final List<ImageComment> comments = imageAdapter.getCommentsForImage(image.get().id); model.addAttribute("image", image.get()); model.addAttribute("comments", comments); return "image"; } @RequestMapping(value = "/comment", method = RequestMethod.POST) public String addComment(final @RequestParam("imageId") String imageId, final @RequestParam("text") String text) { imageAdapter.addComment(imageId, text); return "redirect:/image?id=" + imageId; } @RequestMapping(value = "/postImage", method = RequestMethod.POST) public String postImage(final @RequestParam("title") String title, final @RequestParam("file") MultipartFile file) { if (!file.isEmpty()) { try { final byte[] data = notNull(file.getBytes());
imageAdapter.addImage(new ImageUpload(title, data));
Omegapoint/facepalm
src/main/java/se/omegapoint/facepalm/client/controllers/ImageController.java
// Path: src/main/java/se/omegapoint/facepalm/client/adapters/ImageAdapter.java // @Adapter // public class ImageAdapter { // // private final ImageService imageService; // // @Autowired // public ImageAdapter(final ImageService imageService) { // this.imageService = notNull(imageService); // } // // // public List<ImagePost> getTopImagePosts() { // return imageService.getTopImages().stream() // .map(this::imagePost) // .collect(toList()); // } // // public Optional<ImagePost> getImage(final String id) { // notBlank(id); // // return imageService.getImagePost(id).map(this::imagePost); // } // // public List<ImageComment> getCommentsForImage(final Long imageId) { // notNull(imageId); // // return imageService.getCommentsForImage(imageId).stream() // .map(c -> new ImageComment(c.author, c.text)) // .collect(toList()); // } // // public void addComment(final String imageId, final String text) { // notBlank(imageId); // notBlank(text); // // imageService.addComment(new NewImageComment(Long.valueOf(imageId), currentUser(), text)); // } // // public void addImage(final ImageUpload imageUpload) { // notNull(imageUpload); // imageService.addImagePost(new Title(imageUpload.title), imageUpload.data); // } // // public Image fetchImage(final Long id) { // notNull(id); // return imageService.getImageFor(id); // } // // public String currentUser() { // final AuthenticatedUser authenticatedUser = (AuthenticatedUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); // return authenticatedUser.userName; // } // // private ImagePost imagePost(final se.omegapoint.facepalm.domain.ImagePost image) { // return new ImagePost(image.id, image.title.value, image.numPoints.value, image.numComments.value); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/ImageComment.java // public class ImageComment { // public final String author; // public final String text; // // public ImageComment(final String author, final String text) { // this.author = author; // this.text = text; // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/ImagePost.java // public class ImagePost { // public final Long id; // public final String title; // public final Long numPoints; // public final Long numComments; // // public ImagePost(final Long id, final String title, final Long points, final Long numComments) { // this.id = notNull(id); // this.title = notBlank(title); // this.numPoints = notNull(points); // this.numComments = notNull(numComments); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/ImageUpload.java // public class ImageUpload { // public final String title; // public final byte[] data; // // public ImageUpload(final String title, final byte[] data) { // this.title = notBlank(title); // this.data = notNull(data); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/Image.java // public class Image { // public final byte[] data; // // public Image(final byte[] data) { // this.data = notNull(data); // } // }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import se.omegapoint.facepalm.client.adapters.ImageAdapter; import se.omegapoint.facepalm.client.models.ImageComment; import se.omegapoint.facepalm.client.models.ImagePost; import se.omegapoint.facepalm.client.models.ImageUpload; import se.omegapoint.facepalm.domain.Image; import java.io.IOException; import java.util.List; import java.util.Optional; import static org.apache.commons.lang3.Validate.notNull;
return "redirect:/404"; } final List<ImageComment> comments = imageAdapter.getCommentsForImage(image.get().id); model.addAttribute("image", image.get()); model.addAttribute("comments", comments); return "image"; } @RequestMapping(value = "/comment", method = RequestMethod.POST) public String addComment(final @RequestParam("imageId") String imageId, final @RequestParam("text") String text) { imageAdapter.addComment(imageId, text); return "redirect:/image?id=" + imageId; } @RequestMapping(value = "/postImage", method = RequestMethod.POST) public String postImage(final @RequestParam("title") String title, final @RequestParam("file") MultipartFile file) { if (!file.isEmpty()) { try { final byte[] data = notNull(file.getBytes()); imageAdapter.addImage(new ImageUpload(title, data)); } catch (IOException e) { throw new IllegalArgumentException("Illegal file upload!"); } } return "redirect:/"; } @RequestMapping(value = "/img/{id}") public ResponseEntity<byte[]> image(final @PathVariable("id") String id) {
// Path: src/main/java/se/omegapoint/facepalm/client/adapters/ImageAdapter.java // @Adapter // public class ImageAdapter { // // private final ImageService imageService; // // @Autowired // public ImageAdapter(final ImageService imageService) { // this.imageService = notNull(imageService); // } // // // public List<ImagePost> getTopImagePosts() { // return imageService.getTopImages().stream() // .map(this::imagePost) // .collect(toList()); // } // // public Optional<ImagePost> getImage(final String id) { // notBlank(id); // // return imageService.getImagePost(id).map(this::imagePost); // } // // public List<ImageComment> getCommentsForImage(final Long imageId) { // notNull(imageId); // // return imageService.getCommentsForImage(imageId).stream() // .map(c -> new ImageComment(c.author, c.text)) // .collect(toList()); // } // // public void addComment(final String imageId, final String text) { // notBlank(imageId); // notBlank(text); // // imageService.addComment(new NewImageComment(Long.valueOf(imageId), currentUser(), text)); // } // // public void addImage(final ImageUpload imageUpload) { // notNull(imageUpload); // imageService.addImagePost(new Title(imageUpload.title), imageUpload.data); // } // // public Image fetchImage(final Long id) { // notNull(id); // return imageService.getImageFor(id); // } // // public String currentUser() { // final AuthenticatedUser authenticatedUser = (AuthenticatedUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); // return authenticatedUser.userName; // } // // private ImagePost imagePost(final se.omegapoint.facepalm.domain.ImagePost image) { // return new ImagePost(image.id, image.title.value, image.numPoints.value, image.numComments.value); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/ImageComment.java // public class ImageComment { // public final String author; // public final String text; // // public ImageComment(final String author, final String text) { // this.author = author; // this.text = text; // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/ImagePost.java // public class ImagePost { // public final Long id; // public final String title; // public final Long numPoints; // public final Long numComments; // // public ImagePost(final Long id, final String title, final Long points, final Long numComments) { // this.id = notNull(id); // this.title = notBlank(title); // this.numPoints = notNull(points); // this.numComments = notNull(numComments); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/ImageUpload.java // public class ImageUpload { // public final String title; // public final byte[] data; // // public ImageUpload(final String title, final byte[] data) { // this.title = notBlank(title); // this.data = notNull(data); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/Image.java // public class Image { // public final byte[] data; // // public Image(final byte[] data) { // this.data = notNull(data); // } // } // Path: src/main/java/se/omegapoint/facepalm/client/controllers/ImageController.java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import se.omegapoint.facepalm.client.adapters.ImageAdapter; import se.omegapoint.facepalm.client.models.ImageComment; import se.omegapoint.facepalm.client.models.ImagePost; import se.omegapoint.facepalm.client.models.ImageUpload; import se.omegapoint.facepalm.domain.Image; import java.io.IOException; import java.util.List; import java.util.Optional; import static org.apache.commons.lang3.Validate.notNull; return "redirect:/404"; } final List<ImageComment> comments = imageAdapter.getCommentsForImage(image.get().id); model.addAttribute("image", image.get()); model.addAttribute("comments", comments); return "image"; } @RequestMapping(value = "/comment", method = RequestMethod.POST) public String addComment(final @RequestParam("imageId") String imageId, final @RequestParam("text") String text) { imageAdapter.addComment(imageId, text); return "redirect:/image?id=" + imageId; } @RequestMapping(value = "/postImage", method = RequestMethod.POST) public String postImage(final @RequestParam("title") String title, final @RequestParam("file") MultipartFile file) { if (!file.isEmpty()) { try { final byte[] data = notNull(file.getBytes()); imageAdapter.addImage(new ImageUpload(title, data)); } catch (IOException e) { throw new IllegalArgumentException("Illegal file upload!"); } } return "redirect:/"; } @RequestMapping(value = "/img/{id}") public ResponseEntity<byte[]> image(final @PathVariable("id") String id) {
final Image image = imageAdapter.fetchImage(Long.valueOf(id));
Omegapoint/facepalm
src/main/java/se/omegapoint/facepalm/application/UserService.java
// Path: src/main/java/se/omegapoint/facepalm/domain/NewUserCredentials.java // public class NewUserCredentials { // public final String username; // public final String email; // public final String firstname; // public final String lastname; // public final String password; // // public NewUserCredentials(final String username, final String email, final String firstname, final String lastname, final String password) { // this.username = notBlank(username); // this.email = notBlank(email); // this.firstname = notBlank(firstname); // this.lastname = notBlank(lastname); // this.password = notBlank(password); // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // final NewUserCredentials that = (NewUserCredentials) o; // return Objects.equals(username, that.username) && // Objects.equals(email, that.email) && // Objects.equals(firstname, that.firstname) && // Objects.equals(lastname, that.lastname) && // Objects.equals(password, that.password); // } // // @Override // public int hashCode() { // return Objects.hash(username, email, firstname, lastname, password); // } // // @Override // public String toString() { // return "NewUserCredentials{" + // "username='" + username + '\'' + // ", email='" + email + '\'' + // ", firstname='" + firstname + '\'' + // ", lastname='" + lastname + '\'' + // ", password='" + password + '\'' + // '}'; // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/User.java // public class User { // public final String username; // public final String email; // public final String firstname; // public final String lastname; // // /* // Is there a better way than just using strings I wonder? // */ // public User(final String username, final String email, final String firstname, final String lastname) { // this.username = notBlank(username); // this.email = notBlank(email); // this.firstname = notBlank(firstname); // this.lastname = notBlank(lastname); // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // final User user = (User) o; // return Objects.equals(username, user.username) && // Objects.equals(email, user.email) && // Objects.equals(firstname, user.firstname) && // Objects.equals(lastname, user.lastname); // } // // @Override // public int hashCode() { // return Objects.hash(username, email, firstname, lastname); // } // // @Override // public String toString() { // return "User{" + // "username='" + username + '\'' + // ", email='" + email + '\'' + // ", firstname='" + firstname + '\'' + // ", lastname='" + lastname + '\'' + // '}'; // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/repository/UserRepository.java // public interface UserRepository { // Optional<User> findByUsername(final String username); // // Set<User> findFriendsFor(String username); // // Optional<User> findByNameAndPassword(final String username, final String password); // // List<User> findLike(String value); // // void addFriend(String user, String friend); // // void addUser(NewUserCredentials credentials); // // boolean usersAreFriends(String userA, String userB); // }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import se.omegapoint.facepalm.domain.NewUserCredentials; import se.omegapoint.facepalm.domain.User; import se.omegapoint.facepalm.domain.repository.UserRepository; import java.util.List; import java.util.Optional; import static org.apache.commons.lang3.Validate.notBlank; import static se.omegapoint.facepalm.application.UserService.UserFailure.USER_ALREADY_EXISTS; import static se.omegapoint.facepalm.application.UserService.UserFailure.USER_DOES_NOT_EXIST; import static se.omegapoint.facepalm.application.UserService.UserSuccess.USER_REGISTERD;
/* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.application; @Service public class UserService { @Autowired
// Path: src/main/java/se/omegapoint/facepalm/domain/NewUserCredentials.java // public class NewUserCredentials { // public final String username; // public final String email; // public final String firstname; // public final String lastname; // public final String password; // // public NewUserCredentials(final String username, final String email, final String firstname, final String lastname, final String password) { // this.username = notBlank(username); // this.email = notBlank(email); // this.firstname = notBlank(firstname); // this.lastname = notBlank(lastname); // this.password = notBlank(password); // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // final NewUserCredentials that = (NewUserCredentials) o; // return Objects.equals(username, that.username) && // Objects.equals(email, that.email) && // Objects.equals(firstname, that.firstname) && // Objects.equals(lastname, that.lastname) && // Objects.equals(password, that.password); // } // // @Override // public int hashCode() { // return Objects.hash(username, email, firstname, lastname, password); // } // // @Override // public String toString() { // return "NewUserCredentials{" + // "username='" + username + '\'' + // ", email='" + email + '\'' + // ", firstname='" + firstname + '\'' + // ", lastname='" + lastname + '\'' + // ", password='" + password + '\'' + // '}'; // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/User.java // public class User { // public final String username; // public final String email; // public final String firstname; // public final String lastname; // // /* // Is there a better way than just using strings I wonder? // */ // public User(final String username, final String email, final String firstname, final String lastname) { // this.username = notBlank(username); // this.email = notBlank(email); // this.firstname = notBlank(firstname); // this.lastname = notBlank(lastname); // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // final User user = (User) o; // return Objects.equals(username, user.username) && // Objects.equals(email, user.email) && // Objects.equals(firstname, user.firstname) && // Objects.equals(lastname, user.lastname); // } // // @Override // public int hashCode() { // return Objects.hash(username, email, firstname, lastname); // } // // @Override // public String toString() { // return "User{" + // "username='" + username + '\'' + // ", email='" + email + '\'' + // ", firstname='" + firstname + '\'' + // ", lastname='" + lastname + '\'' + // '}'; // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/repository/UserRepository.java // public interface UserRepository { // Optional<User> findByUsername(final String username); // // Set<User> findFriendsFor(String username); // // Optional<User> findByNameAndPassword(final String username, final String password); // // List<User> findLike(String value); // // void addFriend(String user, String friend); // // void addUser(NewUserCredentials credentials); // // boolean usersAreFriends(String userA, String userB); // } // Path: src/main/java/se/omegapoint/facepalm/application/UserService.java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import se.omegapoint.facepalm.domain.NewUserCredentials; import se.omegapoint.facepalm.domain.User; import se.omegapoint.facepalm.domain.repository.UserRepository; import java.util.List; import java.util.Optional; import static org.apache.commons.lang3.Validate.notBlank; import static se.omegapoint.facepalm.application.UserService.UserFailure.USER_ALREADY_EXISTS; import static se.omegapoint.facepalm.application.UserService.UserFailure.USER_DOES_NOT_EXIST; import static se.omegapoint.facepalm.application.UserService.UserSuccess.USER_REGISTERD; /* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.application; @Service public class UserService { @Autowired
private UserRepository userRepository;
Omegapoint/facepalm
src/main/java/se/omegapoint/facepalm/application/UserService.java
// Path: src/main/java/se/omegapoint/facepalm/domain/NewUserCredentials.java // public class NewUserCredentials { // public final String username; // public final String email; // public final String firstname; // public final String lastname; // public final String password; // // public NewUserCredentials(final String username, final String email, final String firstname, final String lastname, final String password) { // this.username = notBlank(username); // this.email = notBlank(email); // this.firstname = notBlank(firstname); // this.lastname = notBlank(lastname); // this.password = notBlank(password); // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // final NewUserCredentials that = (NewUserCredentials) o; // return Objects.equals(username, that.username) && // Objects.equals(email, that.email) && // Objects.equals(firstname, that.firstname) && // Objects.equals(lastname, that.lastname) && // Objects.equals(password, that.password); // } // // @Override // public int hashCode() { // return Objects.hash(username, email, firstname, lastname, password); // } // // @Override // public String toString() { // return "NewUserCredentials{" + // "username='" + username + '\'' + // ", email='" + email + '\'' + // ", firstname='" + firstname + '\'' + // ", lastname='" + lastname + '\'' + // ", password='" + password + '\'' + // '}'; // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/User.java // public class User { // public final String username; // public final String email; // public final String firstname; // public final String lastname; // // /* // Is there a better way than just using strings I wonder? // */ // public User(final String username, final String email, final String firstname, final String lastname) { // this.username = notBlank(username); // this.email = notBlank(email); // this.firstname = notBlank(firstname); // this.lastname = notBlank(lastname); // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // final User user = (User) o; // return Objects.equals(username, user.username) && // Objects.equals(email, user.email) && // Objects.equals(firstname, user.firstname) && // Objects.equals(lastname, user.lastname); // } // // @Override // public int hashCode() { // return Objects.hash(username, email, firstname, lastname); // } // // @Override // public String toString() { // return "User{" + // "username='" + username + '\'' + // ", email='" + email + '\'' + // ", firstname='" + firstname + '\'' + // ", lastname='" + lastname + '\'' + // '}'; // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/repository/UserRepository.java // public interface UserRepository { // Optional<User> findByUsername(final String username); // // Set<User> findFriendsFor(String username); // // Optional<User> findByNameAndPassword(final String username, final String password); // // List<User> findLike(String value); // // void addFriend(String user, String friend); // // void addUser(NewUserCredentials credentials); // // boolean usersAreFriends(String userA, String userB); // }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import se.omegapoint.facepalm.domain.NewUserCredentials; import se.omegapoint.facepalm.domain.User; import se.omegapoint.facepalm.domain.repository.UserRepository; import java.util.List; import java.util.Optional; import static org.apache.commons.lang3.Validate.notBlank; import static se.omegapoint.facepalm.application.UserService.UserFailure.USER_ALREADY_EXISTS; import static se.omegapoint.facepalm.application.UserService.UserFailure.USER_DOES_NOT_EXIST; import static se.omegapoint.facepalm.application.UserService.UserSuccess.USER_REGISTERD;
/* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.application; @Service public class UserService { @Autowired private UserRepository userRepository; public Result<UserSuccess, UserFailure> registerUser(final String username, final String email, final String firstname, final String lastname, final String password) { notBlank(username); notBlank(email); notBlank(firstname); notBlank(lastname); notBlank(password);
// Path: src/main/java/se/omegapoint/facepalm/domain/NewUserCredentials.java // public class NewUserCredentials { // public final String username; // public final String email; // public final String firstname; // public final String lastname; // public final String password; // // public NewUserCredentials(final String username, final String email, final String firstname, final String lastname, final String password) { // this.username = notBlank(username); // this.email = notBlank(email); // this.firstname = notBlank(firstname); // this.lastname = notBlank(lastname); // this.password = notBlank(password); // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // final NewUserCredentials that = (NewUserCredentials) o; // return Objects.equals(username, that.username) && // Objects.equals(email, that.email) && // Objects.equals(firstname, that.firstname) && // Objects.equals(lastname, that.lastname) && // Objects.equals(password, that.password); // } // // @Override // public int hashCode() { // return Objects.hash(username, email, firstname, lastname, password); // } // // @Override // public String toString() { // return "NewUserCredentials{" + // "username='" + username + '\'' + // ", email='" + email + '\'' + // ", firstname='" + firstname + '\'' + // ", lastname='" + lastname + '\'' + // ", password='" + password + '\'' + // '}'; // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/User.java // public class User { // public final String username; // public final String email; // public final String firstname; // public final String lastname; // // /* // Is there a better way than just using strings I wonder? // */ // public User(final String username, final String email, final String firstname, final String lastname) { // this.username = notBlank(username); // this.email = notBlank(email); // this.firstname = notBlank(firstname); // this.lastname = notBlank(lastname); // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // final User user = (User) o; // return Objects.equals(username, user.username) && // Objects.equals(email, user.email) && // Objects.equals(firstname, user.firstname) && // Objects.equals(lastname, user.lastname); // } // // @Override // public int hashCode() { // return Objects.hash(username, email, firstname, lastname); // } // // @Override // public String toString() { // return "User{" + // "username='" + username + '\'' + // ", email='" + email + '\'' + // ", firstname='" + firstname + '\'' + // ", lastname='" + lastname + '\'' + // '}'; // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/repository/UserRepository.java // public interface UserRepository { // Optional<User> findByUsername(final String username); // // Set<User> findFriendsFor(String username); // // Optional<User> findByNameAndPassword(final String username, final String password); // // List<User> findLike(String value); // // void addFriend(String user, String friend); // // void addUser(NewUserCredentials credentials); // // boolean usersAreFriends(String userA, String userB); // } // Path: src/main/java/se/omegapoint/facepalm/application/UserService.java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import se.omegapoint.facepalm.domain.NewUserCredentials; import se.omegapoint.facepalm.domain.User; import se.omegapoint.facepalm.domain.repository.UserRepository; import java.util.List; import java.util.Optional; import static org.apache.commons.lang3.Validate.notBlank; import static se.omegapoint.facepalm.application.UserService.UserFailure.USER_ALREADY_EXISTS; import static se.omegapoint.facepalm.application.UserService.UserFailure.USER_DOES_NOT_EXIST; import static se.omegapoint.facepalm.application.UserService.UserSuccess.USER_REGISTERD; /* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.application; @Service public class UserService { @Autowired private UserRepository userRepository; public Result<UserSuccess, UserFailure> registerUser(final String username, final String email, final String firstname, final String lastname, final String password) { notBlank(username); notBlank(email); notBlank(firstname); notBlank(lastname); notBlank(password);
final NewUserCredentials credentials = new NewUserCredentials(username, email, firstname, lastname, password);
Omegapoint/facepalm
src/main/java/se/omegapoint/facepalm/application/UserService.java
// Path: src/main/java/se/omegapoint/facepalm/domain/NewUserCredentials.java // public class NewUserCredentials { // public final String username; // public final String email; // public final String firstname; // public final String lastname; // public final String password; // // public NewUserCredentials(final String username, final String email, final String firstname, final String lastname, final String password) { // this.username = notBlank(username); // this.email = notBlank(email); // this.firstname = notBlank(firstname); // this.lastname = notBlank(lastname); // this.password = notBlank(password); // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // final NewUserCredentials that = (NewUserCredentials) o; // return Objects.equals(username, that.username) && // Objects.equals(email, that.email) && // Objects.equals(firstname, that.firstname) && // Objects.equals(lastname, that.lastname) && // Objects.equals(password, that.password); // } // // @Override // public int hashCode() { // return Objects.hash(username, email, firstname, lastname, password); // } // // @Override // public String toString() { // return "NewUserCredentials{" + // "username='" + username + '\'' + // ", email='" + email + '\'' + // ", firstname='" + firstname + '\'' + // ", lastname='" + lastname + '\'' + // ", password='" + password + '\'' + // '}'; // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/User.java // public class User { // public final String username; // public final String email; // public final String firstname; // public final String lastname; // // /* // Is there a better way than just using strings I wonder? // */ // public User(final String username, final String email, final String firstname, final String lastname) { // this.username = notBlank(username); // this.email = notBlank(email); // this.firstname = notBlank(firstname); // this.lastname = notBlank(lastname); // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // final User user = (User) o; // return Objects.equals(username, user.username) && // Objects.equals(email, user.email) && // Objects.equals(firstname, user.firstname) && // Objects.equals(lastname, user.lastname); // } // // @Override // public int hashCode() { // return Objects.hash(username, email, firstname, lastname); // } // // @Override // public String toString() { // return "User{" + // "username='" + username + '\'' + // ", email='" + email + '\'' + // ", firstname='" + firstname + '\'' + // ", lastname='" + lastname + '\'' + // '}'; // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/repository/UserRepository.java // public interface UserRepository { // Optional<User> findByUsername(final String username); // // Set<User> findFriendsFor(String username); // // Optional<User> findByNameAndPassword(final String username, final String password); // // List<User> findLike(String value); // // void addFriend(String user, String friend); // // void addUser(NewUserCredentials credentials); // // boolean usersAreFriends(String userA, String userB); // }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import se.omegapoint.facepalm.domain.NewUserCredentials; import se.omegapoint.facepalm.domain.User; import se.omegapoint.facepalm.domain.repository.UserRepository; import java.util.List; import java.util.Optional; import static org.apache.commons.lang3.Validate.notBlank; import static se.omegapoint.facepalm.application.UserService.UserFailure.USER_ALREADY_EXISTS; import static se.omegapoint.facepalm.application.UserService.UserFailure.USER_DOES_NOT_EXIST; import static se.omegapoint.facepalm.application.UserService.UserSuccess.USER_REGISTERD;
/* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.application; @Service public class UserService { @Autowired private UserRepository userRepository; public Result<UserSuccess, UserFailure> registerUser(final String username, final String email, final String firstname, final String lastname, final String password) { notBlank(username); notBlank(email); notBlank(firstname); notBlank(lastname); notBlank(password); final NewUserCredentials credentials = new NewUserCredentials(username, email, firstname, lastname, password);
// Path: src/main/java/se/omegapoint/facepalm/domain/NewUserCredentials.java // public class NewUserCredentials { // public final String username; // public final String email; // public final String firstname; // public final String lastname; // public final String password; // // public NewUserCredentials(final String username, final String email, final String firstname, final String lastname, final String password) { // this.username = notBlank(username); // this.email = notBlank(email); // this.firstname = notBlank(firstname); // this.lastname = notBlank(lastname); // this.password = notBlank(password); // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // final NewUserCredentials that = (NewUserCredentials) o; // return Objects.equals(username, that.username) && // Objects.equals(email, that.email) && // Objects.equals(firstname, that.firstname) && // Objects.equals(lastname, that.lastname) && // Objects.equals(password, that.password); // } // // @Override // public int hashCode() { // return Objects.hash(username, email, firstname, lastname, password); // } // // @Override // public String toString() { // return "NewUserCredentials{" + // "username='" + username + '\'' + // ", email='" + email + '\'' + // ", firstname='" + firstname + '\'' + // ", lastname='" + lastname + '\'' + // ", password='" + password + '\'' + // '}'; // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/User.java // public class User { // public final String username; // public final String email; // public final String firstname; // public final String lastname; // // /* // Is there a better way than just using strings I wonder? // */ // public User(final String username, final String email, final String firstname, final String lastname) { // this.username = notBlank(username); // this.email = notBlank(email); // this.firstname = notBlank(firstname); // this.lastname = notBlank(lastname); // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // final User user = (User) o; // return Objects.equals(username, user.username) && // Objects.equals(email, user.email) && // Objects.equals(firstname, user.firstname) && // Objects.equals(lastname, user.lastname); // } // // @Override // public int hashCode() { // return Objects.hash(username, email, firstname, lastname); // } // // @Override // public String toString() { // return "User{" + // "username='" + username + '\'' + // ", email='" + email + '\'' + // ", firstname='" + firstname + '\'' + // ", lastname='" + lastname + '\'' + // '}'; // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/repository/UserRepository.java // public interface UserRepository { // Optional<User> findByUsername(final String username); // // Set<User> findFriendsFor(String username); // // Optional<User> findByNameAndPassword(final String username, final String password); // // List<User> findLike(String value); // // void addFriend(String user, String friend); // // void addUser(NewUserCredentials credentials); // // boolean usersAreFriends(String userA, String userB); // } // Path: src/main/java/se/omegapoint/facepalm/application/UserService.java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import se.omegapoint.facepalm.domain.NewUserCredentials; import se.omegapoint.facepalm.domain.User; import se.omegapoint.facepalm.domain.repository.UserRepository; import java.util.List; import java.util.Optional; import static org.apache.commons.lang3.Validate.notBlank; import static se.omegapoint.facepalm.application.UserService.UserFailure.USER_ALREADY_EXISTS; import static se.omegapoint.facepalm.application.UserService.UserFailure.USER_DOES_NOT_EXIST; import static se.omegapoint.facepalm.application.UserService.UserSuccess.USER_REGISTERD; /* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.application; @Service public class UserService { @Autowired private UserRepository userRepository; public Result<UserSuccess, UserFailure> registerUser(final String username, final String email, final String firstname, final String lastname, final String password) { notBlank(username); notBlank(email); notBlank(firstname); notBlank(lastname); notBlank(password); final NewUserCredentials credentials = new NewUserCredentials(username, email, firstname, lastname, password);
final Optional<User> user = getUser(credentials.username);
Omegapoint/facepalm
src/main/java/se/omegapoint/facepalm/client/controllers/PolicyController.java
// Path: src/main/java/se/omegapoint/facepalm/client/adapters/PolicyAdapter.java // @Adapter // public class PolicyAdapter { // // private final PolicyService policyService; // // @Autowired // public PolicyAdapter(final PolicyService policyService) { // this.policyService = notNull(policyService); // } // // public Policy retrievePolicy(final String filename) { // final Optional<se.omegapoint.facepalm.domain.Policy> policy = policyService.retrievePolicy(filename); // return policy.map(p -> new Policy(p.text)).orElseGet(() -> new Policy("Could not load policy")); // } // }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import se.omegapoint.facepalm.client.adapters.PolicyAdapter; import static org.apache.commons.lang3.StringUtils.isBlank; import static org.apache.commons.lang3.Validate.notNull;
/* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.client.controllers; @Controller public class PolicyController {
// Path: src/main/java/se/omegapoint/facepalm/client/adapters/PolicyAdapter.java // @Adapter // public class PolicyAdapter { // // private final PolicyService policyService; // // @Autowired // public PolicyAdapter(final PolicyService policyService) { // this.policyService = notNull(policyService); // } // // public Policy retrievePolicy(final String filename) { // final Optional<se.omegapoint.facepalm.domain.Policy> policy = policyService.retrievePolicy(filename); // return policy.map(p -> new Policy(p.text)).orElseGet(() -> new Policy("Could not load policy")); // } // } // Path: src/main/java/se/omegapoint/facepalm/client/controllers/PolicyController.java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import se.omegapoint.facepalm.client.adapters.PolicyAdapter; import static org.apache.commons.lang3.StringUtils.isBlank; import static org.apache.commons.lang3.Validate.notNull; /* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.client.controllers; @Controller public class PolicyController {
private final PolicyAdapter policyAdapter;
Omegapoint/facepalm
src/main/java/se/omegapoint/facepalm/client/models/Profile.java
// Path: src/main/java/se/omegapoint/facepalm/domain/User.java // public class User { // public final String username; // public final String email; // public final String firstname; // public final String lastname; // // /* // Is there a better way than just using strings I wonder? // */ // public User(final String username, final String email, final String firstname, final String lastname) { // this.username = notBlank(username); // this.email = notBlank(email); // this.firstname = notBlank(firstname); // this.lastname = notBlank(lastname); // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // final User user = (User) o; // return Objects.equals(username, user.username) && // Objects.equals(email, user.email) && // Objects.equals(firstname, user.firstname) && // Objects.equals(lastname, user.lastname); // } // // @Override // public int hashCode() { // return Objects.hash(username, email, firstname, lastname); // } // // @Override // public String toString() { // return "User{" + // "username='" + username + '\'' + // ", email='" + email + '\'' + // ", firstname='" + firstname + '\'' + // ", lastname='" + lastname + '\'' + // '}'; // } // }
import se.omegapoint.facepalm.domain.User; import static org.apache.commons.lang3.Validate.notNull;
/* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.client.models; public class Profile { public String email; public String username; public String firstname; public String lastname;
// Path: src/main/java/se/omegapoint/facepalm/domain/User.java // public class User { // public final String username; // public final String email; // public final String firstname; // public final String lastname; // // /* // Is there a better way than just using strings I wonder? // */ // public User(final String username, final String email, final String firstname, final String lastname) { // this.username = notBlank(username); // this.email = notBlank(email); // this.firstname = notBlank(firstname); // this.lastname = notBlank(lastname); // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // final User user = (User) o; // return Objects.equals(username, user.username) && // Objects.equals(email, user.email) && // Objects.equals(firstname, user.firstname) && // Objects.equals(lastname, user.lastname); // } // // @Override // public int hashCode() { // return Objects.hash(username, email, firstname, lastname); // } // // @Override // public String toString() { // return "User{" + // "username='" + username + '\'' + // ", email='" + email + '\'' + // ", firstname='" + firstname + '\'' + // ", lastname='" + lastname + '\'' + // '}'; // } // } // Path: src/main/java/se/omegapoint/facepalm/client/models/Profile.java import se.omegapoint.facepalm.domain.User; import static org.apache.commons.lang3.Validate.notNull; /* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.client.models; public class Profile { public String email; public String username; public String firstname; public String lastname;
public Profile(final User user) {
Omegapoint/facepalm
src/main/java/se/omegapoint/facepalm/client/controllers/SimpleErrorController.java
// Path: src/main/java/se/omegapoint/facepalm/client/models/User.java // public class User { // public final String username; // // public User(final AuthenticatedUser authenticatedUser) { // notNull(authenticatedUser); // this.username = authenticatedUser.userName; // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/security/AuthenticatedUser.java // public class AuthenticatedUser { // public final String userName; // // public AuthenticatedUser(final String userName) { // this.userName = notBlank(userName); // } // }
import com.google.common.collect.ImmutableMap; import org.springframework.boot.autoconfigure.web.ErrorController; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import se.omegapoint.facepalm.client.models.User; import se.omegapoint.facepalm.client.security.AuthenticatedUser; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Map;
package se.omegapoint.facepalm.client.controllers; @Controller public class SimpleErrorController implements ErrorController { private static final String PATH = "/error"; private static final Map<Integer, String> ERROR_TEXTS = ImmutableMap.of( 404, "The page you were looking for those not exist" // Rest is default ); private static final String DEFAULT_ERROR_MESSAGE = "Oops! An error has occurred. Please contact admin if the problem persists and ask them to check the logs."; @RequestMapping(value = PATH) public String error(final HttpServletRequest servletRequest, final HttpServletResponse servletResponse, final Model model) { model.addAttribute("user", user()); model.addAttribute("errorText", mapFromStatus(servletResponse.getStatus())); return "error"; } @Override public String getErrorPath() { return PATH; }
// Path: src/main/java/se/omegapoint/facepalm/client/models/User.java // public class User { // public final String username; // // public User(final AuthenticatedUser authenticatedUser) { // notNull(authenticatedUser); // this.username = authenticatedUser.userName; // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/security/AuthenticatedUser.java // public class AuthenticatedUser { // public final String userName; // // public AuthenticatedUser(final String userName) { // this.userName = notBlank(userName); // } // } // Path: src/main/java/se/omegapoint/facepalm/client/controllers/SimpleErrorController.java import com.google.common.collect.ImmutableMap; import org.springframework.boot.autoconfigure.web.ErrorController; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import se.omegapoint.facepalm.client.models.User; import se.omegapoint.facepalm.client.security.AuthenticatedUser; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Map; package se.omegapoint.facepalm.client.controllers; @Controller public class SimpleErrorController implements ErrorController { private static final String PATH = "/error"; private static final Map<Integer, String> ERROR_TEXTS = ImmutableMap.of( 404, "The page you were looking for those not exist" // Rest is default ); private static final String DEFAULT_ERROR_MESSAGE = "Oops! An error has occurred. Please contact admin if the problem persists and ask them to check the logs."; @RequestMapping(value = PATH) public String error(final HttpServletRequest servletRequest, final HttpServletResponse servletResponse, final Model model) { model.addAttribute("user", user()); model.addAttribute("errorText", mapFromStatus(servletResponse.getStatus())); return "error"; } @Override public String getErrorPath() { return PATH; }
public User user() {
Omegapoint/facepalm
src/main/java/se/omegapoint/facepalm/client/controllers/SimpleErrorController.java
// Path: src/main/java/se/omegapoint/facepalm/client/models/User.java // public class User { // public final String username; // // public User(final AuthenticatedUser authenticatedUser) { // notNull(authenticatedUser); // this.username = authenticatedUser.userName; // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/security/AuthenticatedUser.java // public class AuthenticatedUser { // public final String userName; // // public AuthenticatedUser(final String userName) { // this.userName = notBlank(userName); // } // }
import com.google.common.collect.ImmutableMap; import org.springframework.boot.autoconfigure.web.ErrorController; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import se.omegapoint.facepalm.client.models.User; import se.omegapoint.facepalm.client.security.AuthenticatedUser; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Map;
package se.omegapoint.facepalm.client.controllers; @Controller public class SimpleErrorController implements ErrorController { private static final String PATH = "/error"; private static final Map<Integer, String> ERROR_TEXTS = ImmutableMap.of( 404, "The page you were looking for those not exist" // Rest is default ); private static final String DEFAULT_ERROR_MESSAGE = "Oops! An error has occurred. Please contact admin if the problem persists and ask them to check the logs."; @RequestMapping(value = PATH) public String error(final HttpServletRequest servletRequest, final HttpServletResponse servletResponse, final Model model) { model.addAttribute("user", user()); model.addAttribute("errorText", mapFromStatus(servletResponse.getStatus())); return "error"; } @Override public String getErrorPath() { return PATH; } public User user() { if (SecurityContextHolder.getContext().getAuthentication() instanceof UsernamePasswordAuthenticationToken) {
// Path: src/main/java/se/omegapoint/facepalm/client/models/User.java // public class User { // public final String username; // // public User(final AuthenticatedUser authenticatedUser) { // notNull(authenticatedUser); // this.username = authenticatedUser.userName; // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/security/AuthenticatedUser.java // public class AuthenticatedUser { // public final String userName; // // public AuthenticatedUser(final String userName) { // this.userName = notBlank(userName); // } // } // Path: src/main/java/se/omegapoint/facepalm/client/controllers/SimpleErrorController.java import com.google.common.collect.ImmutableMap; import org.springframework.boot.autoconfigure.web.ErrorController; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import se.omegapoint.facepalm.client.models.User; import se.omegapoint.facepalm.client.security.AuthenticatedUser; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Map; package se.omegapoint.facepalm.client.controllers; @Controller public class SimpleErrorController implements ErrorController { private static final String PATH = "/error"; private static final Map<Integer, String> ERROR_TEXTS = ImmutableMap.of( 404, "The page you were looking for those not exist" // Rest is default ); private static final String DEFAULT_ERROR_MESSAGE = "Oops! An error has occurred. Please contact admin if the problem persists and ask them to check the logs."; @RequestMapping(value = PATH) public String error(final HttpServletRequest servletRequest, final HttpServletResponse servletResponse, final Model model) { model.addAttribute("user", user()); model.addAttribute("errorText", mapFromStatus(servletResponse.getStatus())); return "error"; } @Override public String getErrorPath() { return PATH; } public User user() { if (SecurityContextHolder.getContext().getAuthentication() instanceof UsernamePasswordAuthenticationToken) {
final AuthenticatedUser authenticatedUser = (AuthenticatedUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
Omegapoint/facepalm
src/main/java/se/omegapoint/facepalm/infrastructure/db/ImagePost.java
// Path: src/main/java/se/omegapoint/facepalm/domain/Title.java // public class Title { // private static final int MAN_LENGTH = 100; // // public final String value; // // public Title(final String value) { // this.value = notBlank(value); // isTrue(this.value.length() < MAN_LENGTH, "Title can be maximum 100 characters"); // } // }
import se.omegapoint.facepalm.domain.Title; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.persistence.Table;
public Long getNumComments() { return numComments; } public void setNumComments(Long numComments) { this.numComments = numComments; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Long getPoints() { return points; } public void setPoints(Long points) { this.points = points; } public static class Builder { private String title; private StoredImage storedImage; private Long numComments; private Long points;
// Path: src/main/java/se/omegapoint/facepalm/domain/Title.java // public class Title { // private static final int MAN_LENGTH = 100; // // public final String value; // // public Title(final String value) { // this.value = notBlank(value); // isTrue(this.value.length() < MAN_LENGTH, "Title can be maximum 100 characters"); // } // } // Path: src/main/java/se/omegapoint/facepalm/infrastructure/db/ImagePost.java import se.omegapoint.facepalm.domain.Title; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.persistence.Table; public Long getNumComments() { return numComments; } public void setNumComments(Long numComments) { this.numComments = numComments; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Long getPoints() { return points; } public void setPoints(Long points) { this.points = points; } public static class Builder { private String title; private StoredImage storedImage; private Long numComments; private Long points;
public Builder withTitle(final Title title) {
Omegapoint/facepalm
src/main/java/se/omegapoint/facepalm/application/CommercialService.java
// Path: src/main/java/se/omegapoint/facepalm/domain/Commercial.java // public class Commercial { // public final String title; // public final String uri; // // public Commercial(String title, String uri) { // this.title = title; // this.uri = uri; // } // }
import com.google.common.collect.ImmutableList; import org.springframework.stereotype.Service; import se.omegapoint.facepalm.domain.Commercial; import java.util.List;
/* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.application; @Service public class CommercialService {
// Path: src/main/java/se/omegapoint/facepalm/domain/Commercial.java // public class Commercial { // public final String title; // public final String uri; // // public Commercial(String title, String uri) { // this.title = title; // this.uri = uri; // } // } // Path: src/main/java/se/omegapoint/facepalm/application/CommercialService.java import com.google.common.collect.ImmutableList; import org.springframework.stereotype.Service; import se.omegapoint.facepalm.domain.Commercial; import java.util.List; /* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.application; @Service public class CommercialService {
public List<Commercial> getCommercials() {
Omegapoint/facepalm
src/main/java/se/omegapoint/facepalm/client/adapters/PolicyAdapter.java
// Path: src/main/java/se/omegapoint/facepalm/application/PolicyService.java // @Service // public class PolicyService { // // private final PolicyRepository policyRepository; // // @Autowired // public PolicyService(final PolicyRepository policyRepository) { // this.policyRepository = notNull(policyRepository); // } // // public Optional<Policy> retrievePolicy(final String filename) { // notBlank(filename); // return policyRepository.retrievePolicyWith(filename); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/Policy.java // public class Policy { // public final String text; // // public Policy(final String text) { // this.text = notBlank(text); // } // }
import org.springframework.beans.factory.annotation.Autowired; import se.omegapoint.facepalm.application.PolicyService; import se.omegapoint.facepalm.client.config.Adapter; import se.omegapoint.facepalm.client.models.Policy; import java.util.Optional; import static org.apache.commons.lang3.Validate.notNull;
/* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.client.adapters; @Adapter public class PolicyAdapter {
// Path: src/main/java/se/omegapoint/facepalm/application/PolicyService.java // @Service // public class PolicyService { // // private final PolicyRepository policyRepository; // // @Autowired // public PolicyService(final PolicyRepository policyRepository) { // this.policyRepository = notNull(policyRepository); // } // // public Optional<Policy> retrievePolicy(final String filename) { // notBlank(filename); // return policyRepository.retrievePolicyWith(filename); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/Policy.java // public class Policy { // public final String text; // // public Policy(final String text) { // this.text = notBlank(text); // } // } // Path: src/main/java/se/omegapoint/facepalm/client/adapters/PolicyAdapter.java import org.springframework.beans.factory.annotation.Autowired; import se.omegapoint.facepalm.application.PolicyService; import se.omegapoint.facepalm.client.config.Adapter; import se.omegapoint.facepalm.client.models.Policy; import java.util.Optional; import static org.apache.commons.lang3.Validate.notNull; /* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.client.adapters; @Adapter public class PolicyAdapter {
private final PolicyService policyService;
Omegapoint/facepalm
src/main/java/se/omegapoint/facepalm/client/adapters/PolicyAdapter.java
// Path: src/main/java/se/omegapoint/facepalm/application/PolicyService.java // @Service // public class PolicyService { // // private final PolicyRepository policyRepository; // // @Autowired // public PolicyService(final PolicyRepository policyRepository) { // this.policyRepository = notNull(policyRepository); // } // // public Optional<Policy> retrievePolicy(final String filename) { // notBlank(filename); // return policyRepository.retrievePolicyWith(filename); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/Policy.java // public class Policy { // public final String text; // // public Policy(final String text) { // this.text = notBlank(text); // } // }
import org.springframework.beans.factory.annotation.Autowired; import se.omegapoint.facepalm.application.PolicyService; import se.omegapoint.facepalm.client.config.Adapter; import se.omegapoint.facepalm.client.models.Policy; import java.util.Optional; import static org.apache.commons.lang3.Validate.notNull;
/* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.client.adapters; @Adapter public class PolicyAdapter { private final PolicyService policyService; @Autowired public PolicyAdapter(final PolicyService policyService) { this.policyService = notNull(policyService); }
// Path: src/main/java/se/omegapoint/facepalm/application/PolicyService.java // @Service // public class PolicyService { // // private final PolicyRepository policyRepository; // // @Autowired // public PolicyService(final PolicyRepository policyRepository) { // this.policyRepository = notNull(policyRepository); // } // // public Optional<Policy> retrievePolicy(final String filename) { // notBlank(filename); // return policyRepository.retrievePolicyWith(filename); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/Policy.java // public class Policy { // public final String text; // // public Policy(final String text) { // this.text = notBlank(text); // } // } // Path: src/main/java/se/omegapoint/facepalm/client/adapters/PolicyAdapter.java import org.springframework.beans.factory.annotation.Autowired; import se.omegapoint.facepalm.application.PolicyService; import se.omegapoint.facepalm.client.config.Adapter; import se.omegapoint.facepalm.client.models.Policy; import java.util.Optional; import static org.apache.commons.lang3.Validate.notNull; /* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.client.adapters; @Adapter public class PolicyAdapter { private final PolicyService policyService; @Autowired public PolicyAdapter(final PolicyService policyService) { this.policyService = notNull(policyService); }
public Policy retrievePolicy(final String filename) {
Omegapoint/facepalm
src/main/java/se/omegapoint/facepalm/domain/repository/ImageRepository.java
// Path: src/main/java/se/omegapoint/facepalm/domain/Image.java // public class Image { // public final byte[] data; // // public Image(final byte[] data) { // this.data = notNull(data); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/ImagePost.java // public class ImagePost { // public final Long id; // public final Title title; // public final NumberOfPoints numPoints; // public final NumberOfComments numComments; // // public ImagePost(final Long id, final Title title, final NumberOfPoints points, final NumberOfComments numComments) { // this.id = notNull(id); // this.title = notNull(title); // this.numPoints = notNull(points); // this.numComments = notNull(numComments); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/Title.java // public class Title { // private static final int MAN_LENGTH = 100; // // public final String value; // // public Title(final String value) { // this.value = notBlank(value); // isTrue(this.value.length() < MAN_LENGTH, "Title can be maximum 100 characters"); // } // }
import se.omegapoint.facepalm.domain.Image; import se.omegapoint.facepalm.domain.ImagePost; import se.omegapoint.facepalm.domain.Title; import java.util.List; import java.util.Optional;
/* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.domain.repository; public interface ImageRepository { List<ImagePost> findAll(); Optional<ImagePost> findById(String id);
// Path: src/main/java/se/omegapoint/facepalm/domain/Image.java // public class Image { // public final byte[] data; // // public Image(final byte[] data) { // this.data = notNull(data); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/ImagePost.java // public class ImagePost { // public final Long id; // public final Title title; // public final NumberOfPoints numPoints; // public final NumberOfComments numComments; // // public ImagePost(final Long id, final Title title, final NumberOfPoints points, final NumberOfComments numComments) { // this.id = notNull(id); // this.title = notNull(title); // this.numPoints = notNull(points); // this.numComments = notNull(numComments); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/Title.java // public class Title { // private static final int MAN_LENGTH = 100; // // public final String value; // // public Title(final String value) { // this.value = notBlank(value); // isTrue(this.value.length() < MAN_LENGTH, "Title can be maximum 100 characters"); // } // } // Path: src/main/java/se/omegapoint/facepalm/domain/repository/ImageRepository.java import se.omegapoint.facepalm.domain.Image; import se.omegapoint.facepalm.domain.ImagePost; import se.omegapoint.facepalm.domain.Title; import java.util.List; import java.util.Optional; /* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.domain.repository; public interface ImageRepository { List<ImagePost> findAll(); Optional<ImagePost> findById(String id);
void addImagePost(Title title, byte[] data);
Omegapoint/facepalm
src/main/java/se/omegapoint/facepalm/domain/repository/ImageRepository.java
// Path: src/main/java/se/omegapoint/facepalm/domain/Image.java // public class Image { // public final byte[] data; // // public Image(final byte[] data) { // this.data = notNull(data); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/ImagePost.java // public class ImagePost { // public final Long id; // public final Title title; // public final NumberOfPoints numPoints; // public final NumberOfComments numComments; // // public ImagePost(final Long id, final Title title, final NumberOfPoints points, final NumberOfComments numComments) { // this.id = notNull(id); // this.title = notNull(title); // this.numPoints = notNull(points); // this.numComments = notNull(numComments); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/Title.java // public class Title { // private static final int MAN_LENGTH = 100; // // public final String value; // // public Title(final String value) { // this.value = notBlank(value); // isTrue(this.value.length() < MAN_LENGTH, "Title can be maximum 100 characters"); // } // }
import se.omegapoint.facepalm.domain.Image; import se.omegapoint.facepalm.domain.ImagePost; import se.omegapoint.facepalm.domain.Title; import java.util.List; import java.util.Optional;
/* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.domain.repository; public interface ImageRepository { List<ImagePost> findAll(); Optional<ImagePost> findById(String id); void addImagePost(Title title, byte[] data);
// Path: src/main/java/se/omegapoint/facepalm/domain/Image.java // public class Image { // public final byte[] data; // // public Image(final byte[] data) { // this.data = notNull(data); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/ImagePost.java // public class ImagePost { // public final Long id; // public final Title title; // public final NumberOfPoints numPoints; // public final NumberOfComments numComments; // // public ImagePost(final Long id, final Title title, final NumberOfPoints points, final NumberOfComments numComments) { // this.id = notNull(id); // this.title = notNull(title); // this.numPoints = notNull(points); // this.numComments = notNull(numComments); // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/Title.java // public class Title { // private static final int MAN_LENGTH = 100; // // public final String value; // // public Title(final String value) { // this.value = notBlank(value); // isTrue(this.value.length() < MAN_LENGTH, "Title can be maximum 100 characters"); // } // } // Path: src/main/java/se/omegapoint/facepalm/domain/repository/ImageRepository.java import se.omegapoint.facepalm.domain.Image; import se.omegapoint.facepalm.domain.ImagePost; import se.omegapoint.facepalm.domain.Title; import java.util.List; import java.util.Optional; /* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.domain.repository; public interface ImageRepository { List<ImagePost> findAll(); Optional<ImagePost> findById(String id); void addImagePost(Title title, byte[] data);
Image findImageByPostId(Long id);
Omegapoint/facepalm
src/main/java/se/omegapoint/facepalm/infrastructure/JPACommentRepository.java
// Path: src/main/java/se/omegapoint/facepalm/domain/ImageComment.java // public class ImageComment { // // public final Long imageId; // public final String author; // public final String text; // // public ImageComment(final Long imageId, final String author, final String text) { // this.imageId = imageId; // this.author = author; // this.text = text; // } // // @Override // public String toString() { // return "ImageComment{" + // "imageId=" + imageId + // ", author='" + author + '\'' + // ", text='" + text + '\'' + // '}'; // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/event/EventService.java // public interface EventService { // void publish(ApplicationEvent event); // } // // Path: src/main/java/se/omegapoint/facepalm/domain/repository/CommentRepository.java // public interface CommentRepository { // List<ImageComment> findByImageId(final Long id); // // void addComment(Long imageId, String author, String text); // } // // Path: src/main/java/se/omegapoint/facepalm/infrastructure/db/Comment.java // @Entity // @Table(name = "COMMENTS") // public class Comment { // @Id // @GeneratedValue // @Column(name = "ID") // private Long id; // // @Column(name = "IMAGE_ID") // private Long imageId; // // @Column(name = "AUTHOR") // private String author; // // @Column(name = "COMMENT") // private String comment; // // public Comment() { // // JPA // } // // public Comment(final Long imageId, final String author, final String comment) { // this.imageId = notNull(imageId); // this.author = notBlank(author); // this.comment = notBlank(comment); // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getImageId() { // return imageId; // } // // public void setImageId(Long imageId) { // this.imageId = imageId; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getComment() { // return comment; // } // // public void setComment(String comment) { // this.comment = comment; // } // } // // Path: src/main/java/se/omegapoint/facepalm/infrastructure/event/GenericEvent.java // public class GenericEvent implements ApplicationEvent { // private final Object data; // // public GenericEvent(final Object data) { // this.data = notNull(data); // } // // @Override // public String message() { // return data.toString(); // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // final GenericEvent that = (GenericEvent) o; // return Objects.equals(data, that.data); // } // // @Override // public int hashCode() { // return Objects.hash(data); // } // }
import static java.util.stream.Collectors.toList; import static org.apache.commons.lang3.Validate.notNull; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import se.omegapoint.facepalm.domain.ImageComment; import se.omegapoint.facepalm.domain.event.EventService; import se.omegapoint.facepalm.domain.repository.CommentRepository; import se.omegapoint.facepalm.infrastructure.db.Comment; import se.omegapoint.facepalm.infrastructure.event.GenericEvent; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import java.util.List; import static java.lang.String.format;
/* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.infrastructure; @Repository @Transactional
// Path: src/main/java/se/omegapoint/facepalm/domain/ImageComment.java // public class ImageComment { // // public final Long imageId; // public final String author; // public final String text; // // public ImageComment(final Long imageId, final String author, final String text) { // this.imageId = imageId; // this.author = author; // this.text = text; // } // // @Override // public String toString() { // return "ImageComment{" + // "imageId=" + imageId + // ", author='" + author + '\'' + // ", text='" + text + '\'' + // '}'; // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/event/EventService.java // public interface EventService { // void publish(ApplicationEvent event); // } // // Path: src/main/java/se/omegapoint/facepalm/domain/repository/CommentRepository.java // public interface CommentRepository { // List<ImageComment> findByImageId(final Long id); // // void addComment(Long imageId, String author, String text); // } // // Path: src/main/java/se/omegapoint/facepalm/infrastructure/db/Comment.java // @Entity // @Table(name = "COMMENTS") // public class Comment { // @Id // @GeneratedValue // @Column(name = "ID") // private Long id; // // @Column(name = "IMAGE_ID") // private Long imageId; // // @Column(name = "AUTHOR") // private String author; // // @Column(name = "COMMENT") // private String comment; // // public Comment() { // // JPA // } // // public Comment(final Long imageId, final String author, final String comment) { // this.imageId = notNull(imageId); // this.author = notBlank(author); // this.comment = notBlank(comment); // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getImageId() { // return imageId; // } // // public void setImageId(Long imageId) { // this.imageId = imageId; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getComment() { // return comment; // } // // public void setComment(String comment) { // this.comment = comment; // } // } // // Path: src/main/java/se/omegapoint/facepalm/infrastructure/event/GenericEvent.java // public class GenericEvent implements ApplicationEvent { // private final Object data; // // public GenericEvent(final Object data) { // this.data = notNull(data); // } // // @Override // public String message() { // return data.toString(); // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // final GenericEvent that = (GenericEvent) o; // return Objects.equals(data, that.data); // } // // @Override // public int hashCode() { // return Objects.hash(data); // } // } // Path: src/main/java/se/omegapoint/facepalm/infrastructure/JPACommentRepository.java import static java.util.stream.Collectors.toList; import static org.apache.commons.lang3.Validate.notNull; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import se.omegapoint.facepalm.domain.ImageComment; import se.omegapoint.facepalm.domain.event.EventService; import se.omegapoint.facepalm.domain.repository.CommentRepository; import se.omegapoint.facepalm.infrastructure.db.Comment; import se.omegapoint.facepalm.infrastructure.event.GenericEvent; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import java.util.List; import static java.lang.String.format; /* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.infrastructure; @Repository @Transactional
public class JPACommentRepository implements CommentRepository {
Omegapoint/facepalm
src/main/java/se/omegapoint/facepalm/infrastructure/JPACommentRepository.java
// Path: src/main/java/se/omegapoint/facepalm/domain/ImageComment.java // public class ImageComment { // // public final Long imageId; // public final String author; // public final String text; // // public ImageComment(final Long imageId, final String author, final String text) { // this.imageId = imageId; // this.author = author; // this.text = text; // } // // @Override // public String toString() { // return "ImageComment{" + // "imageId=" + imageId + // ", author='" + author + '\'' + // ", text='" + text + '\'' + // '}'; // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/event/EventService.java // public interface EventService { // void publish(ApplicationEvent event); // } // // Path: src/main/java/se/omegapoint/facepalm/domain/repository/CommentRepository.java // public interface CommentRepository { // List<ImageComment> findByImageId(final Long id); // // void addComment(Long imageId, String author, String text); // } // // Path: src/main/java/se/omegapoint/facepalm/infrastructure/db/Comment.java // @Entity // @Table(name = "COMMENTS") // public class Comment { // @Id // @GeneratedValue // @Column(name = "ID") // private Long id; // // @Column(name = "IMAGE_ID") // private Long imageId; // // @Column(name = "AUTHOR") // private String author; // // @Column(name = "COMMENT") // private String comment; // // public Comment() { // // JPA // } // // public Comment(final Long imageId, final String author, final String comment) { // this.imageId = notNull(imageId); // this.author = notBlank(author); // this.comment = notBlank(comment); // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getImageId() { // return imageId; // } // // public void setImageId(Long imageId) { // this.imageId = imageId; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getComment() { // return comment; // } // // public void setComment(String comment) { // this.comment = comment; // } // } // // Path: src/main/java/se/omegapoint/facepalm/infrastructure/event/GenericEvent.java // public class GenericEvent implements ApplicationEvent { // private final Object data; // // public GenericEvent(final Object data) { // this.data = notNull(data); // } // // @Override // public String message() { // return data.toString(); // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // final GenericEvent that = (GenericEvent) o; // return Objects.equals(data, that.data); // } // // @Override // public int hashCode() { // return Objects.hash(data); // } // }
import static java.util.stream.Collectors.toList; import static org.apache.commons.lang3.Validate.notNull; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import se.omegapoint.facepalm.domain.ImageComment; import se.omegapoint.facepalm.domain.event.EventService; import se.omegapoint.facepalm.domain.repository.CommentRepository; import se.omegapoint.facepalm.infrastructure.db.Comment; import se.omegapoint.facepalm.infrastructure.event.GenericEvent; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import java.util.List; import static java.lang.String.format;
/* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.infrastructure; @Repository @Transactional public class JPACommentRepository implements CommentRepository {
// Path: src/main/java/se/omegapoint/facepalm/domain/ImageComment.java // public class ImageComment { // // public final Long imageId; // public final String author; // public final String text; // // public ImageComment(final Long imageId, final String author, final String text) { // this.imageId = imageId; // this.author = author; // this.text = text; // } // // @Override // public String toString() { // return "ImageComment{" + // "imageId=" + imageId + // ", author='" + author + '\'' + // ", text='" + text + '\'' + // '}'; // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/event/EventService.java // public interface EventService { // void publish(ApplicationEvent event); // } // // Path: src/main/java/se/omegapoint/facepalm/domain/repository/CommentRepository.java // public interface CommentRepository { // List<ImageComment> findByImageId(final Long id); // // void addComment(Long imageId, String author, String text); // } // // Path: src/main/java/se/omegapoint/facepalm/infrastructure/db/Comment.java // @Entity // @Table(name = "COMMENTS") // public class Comment { // @Id // @GeneratedValue // @Column(name = "ID") // private Long id; // // @Column(name = "IMAGE_ID") // private Long imageId; // // @Column(name = "AUTHOR") // private String author; // // @Column(name = "COMMENT") // private String comment; // // public Comment() { // // JPA // } // // public Comment(final Long imageId, final String author, final String comment) { // this.imageId = notNull(imageId); // this.author = notBlank(author); // this.comment = notBlank(comment); // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getImageId() { // return imageId; // } // // public void setImageId(Long imageId) { // this.imageId = imageId; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getComment() { // return comment; // } // // public void setComment(String comment) { // this.comment = comment; // } // } // // Path: src/main/java/se/omegapoint/facepalm/infrastructure/event/GenericEvent.java // public class GenericEvent implements ApplicationEvent { // private final Object data; // // public GenericEvent(final Object data) { // this.data = notNull(data); // } // // @Override // public String message() { // return data.toString(); // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // final GenericEvent that = (GenericEvent) o; // return Objects.equals(data, that.data); // } // // @Override // public int hashCode() { // return Objects.hash(data); // } // } // Path: src/main/java/se/omegapoint/facepalm/infrastructure/JPACommentRepository.java import static java.util.stream.Collectors.toList; import static org.apache.commons.lang3.Validate.notNull; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import se.omegapoint.facepalm.domain.ImageComment; import se.omegapoint.facepalm.domain.event.EventService; import se.omegapoint.facepalm.domain.repository.CommentRepository; import se.omegapoint.facepalm.infrastructure.db.Comment; import se.omegapoint.facepalm.infrastructure.event.GenericEvent; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import java.util.List; import static java.lang.String.format; /* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.infrastructure; @Repository @Transactional public class JPACommentRepository implements CommentRepository {
private final EventService eventService;
Omegapoint/facepalm
src/main/java/se/omegapoint/facepalm/infrastructure/JPACommentRepository.java
// Path: src/main/java/se/omegapoint/facepalm/domain/ImageComment.java // public class ImageComment { // // public final Long imageId; // public final String author; // public final String text; // // public ImageComment(final Long imageId, final String author, final String text) { // this.imageId = imageId; // this.author = author; // this.text = text; // } // // @Override // public String toString() { // return "ImageComment{" + // "imageId=" + imageId + // ", author='" + author + '\'' + // ", text='" + text + '\'' + // '}'; // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/event/EventService.java // public interface EventService { // void publish(ApplicationEvent event); // } // // Path: src/main/java/se/omegapoint/facepalm/domain/repository/CommentRepository.java // public interface CommentRepository { // List<ImageComment> findByImageId(final Long id); // // void addComment(Long imageId, String author, String text); // } // // Path: src/main/java/se/omegapoint/facepalm/infrastructure/db/Comment.java // @Entity // @Table(name = "COMMENTS") // public class Comment { // @Id // @GeneratedValue // @Column(name = "ID") // private Long id; // // @Column(name = "IMAGE_ID") // private Long imageId; // // @Column(name = "AUTHOR") // private String author; // // @Column(name = "COMMENT") // private String comment; // // public Comment() { // // JPA // } // // public Comment(final Long imageId, final String author, final String comment) { // this.imageId = notNull(imageId); // this.author = notBlank(author); // this.comment = notBlank(comment); // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getImageId() { // return imageId; // } // // public void setImageId(Long imageId) { // this.imageId = imageId; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getComment() { // return comment; // } // // public void setComment(String comment) { // this.comment = comment; // } // } // // Path: src/main/java/se/omegapoint/facepalm/infrastructure/event/GenericEvent.java // public class GenericEvent implements ApplicationEvent { // private final Object data; // // public GenericEvent(final Object data) { // this.data = notNull(data); // } // // @Override // public String message() { // return data.toString(); // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // final GenericEvent that = (GenericEvent) o; // return Objects.equals(data, that.data); // } // // @Override // public int hashCode() { // return Objects.hash(data); // } // }
import static java.util.stream.Collectors.toList; import static org.apache.commons.lang3.Validate.notNull; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import se.omegapoint.facepalm.domain.ImageComment; import se.omegapoint.facepalm.domain.event.EventService; import se.omegapoint.facepalm.domain.repository.CommentRepository; import se.omegapoint.facepalm.infrastructure.db.Comment; import se.omegapoint.facepalm.infrastructure.event.GenericEvent; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import java.util.List; import static java.lang.String.format;
/* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.infrastructure; @Repository @Transactional public class JPACommentRepository implements CommentRepository { private final EventService eventService; @PersistenceContext private EntityManager entityManager; @Autowired public JPACommentRepository(final EventService eventService) { this.eventService = notNull(eventService); } @Override
// Path: src/main/java/se/omegapoint/facepalm/domain/ImageComment.java // public class ImageComment { // // public final Long imageId; // public final String author; // public final String text; // // public ImageComment(final Long imageId, final String author, final String text) { // this.imageId = imageId; // this.author = author; // this.text = text; // } // // @Override // public String toString() { // return "ImageComment{" + // "imageId=" + imageId + // ", author='" + author + '\'' + // ", text='" + text + '\'' + // '}'; // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/event/EventService.java // public interface EventService { // void publish(ApplicationEvent event); // } // // Path: src/main/java/se/omegapoint/facepalm/domain/repository/CommentRepository.java // public interface CommentRepository { // List<ImageComment> findByImageId(final Long id); // // void addComment(Long imageId, String author, String text); // } // // Path: src/main/java/se/omegapoint/facepalm/infrastructure/db/Comment.java // @Entity // @Table(name = "COMMENTS") // public class Comment { // @Id // @GeneratedValue // @Column(name = "ID") // private Long id; // // @Column(name = "IMAGE_ID") // private Long imageId; // // @Column(name = "AUTHOR") // private String author; // // @Column(name = "COMMENT") // private String comment; // // public Comment() { // // JPA // } // // public Comment(final Long imageId, final String author, final String comment) { // this.imageId = notNull(imageId); // this.author = notBlank(author); // this.comment = notBlank(comment); // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getImageId() { // return imageId; // } // // public void setImageId(Long imageId) { // this.imageId = imageId; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getComment() { // return comment; // } // // public void setComment(String comment) { // this.comment = comment; // } // } // // Path: src/main/java/se/omegapoint/facepalm/infrastructure/event/GenericEvent.java // public class GenericEvent implements ApplicationEvent { // private final Object data; // // public GenericEvent(final Object data) { // this.data = notNull(data); // } // // @Override // public String message() { // return data.toString(); // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // final GenericEvent that = (GenericEvent) o; // return Objects.equals(data, that.data); // } // // @Override // public int hashCode() { // return Objects.hash(data); // } // } // Path: src/main/java/se/omegapoint/facepalm/infrastructure/JPACommentRepository.java import static java.util.stream.Collectors.toList; import static org.apache.commons.lang3.Validate.notNull; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import se.omegapoint.facepalm.domain.ImageComment; import se.omegapoint.facepalm.domain.event.EventService; import se.omegapoint.facepalm.domain.repository.CommentRepository; import se.omegapoint.facepalm.infrastructure.db.Comment; import se.omegapoint.facepalm.infrastructure.event.GenericEvent; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import java.util.List; import static java.lang.String.format; /* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.infrastructure; @Repository @Transactional public class JPACommentRepository implements CommentRepository { private final EventService eventService; @PersistenceContext private EntityManager entityManager; @Autowired public JPACommentRepository(final EventService eventService) { this.eventService = notNull(eventService); } @Override
public List<ImageComment> findByImageId(final Long id) {
Omegapoint/facepalm
src/main/java/se/omegapoint/facepalm/infrastructure/JPACommentRepository.java
// Path: src/main/java/se/omegapoint/facepalm/domain/ImageComment.java // public class ImageComment { // // public final Long imageId; // public final String author; // public final String text; // // public ImageComment(final Long imageId, final String author, final String text) { // this.imageId = imageId; // this.author = author; // this.text = text; // } // // @Override // public String toString() { // return "ImageComment{" + // "imageId=" + imageId + // ", author='" + author + '\'' + // ", text='" + text + '\'' + // '}'; // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/event/EventService.java // public interface EventService { // void publish(ApplicationEvent event); // } // // Path: src/main/java/se/omegapoint/facepalm/domain/repository/CommentRepository.java // public interface CommentRepository { // List<ImageComment> findByImageId(final Long id); // // void addComment(Long imageId, String author, String text); // } // // Path: src/main/java/se/omegapoint/facepalm/infrastructure/db/Comment.java // @Entity // @Table(name = "COMMENTS") // public class Comment { // @Id // @GeneratedValue // @Column(name = "ID") // private Long id; // // @Column(name = "IMAGE_ID") // private Long imageId; // // @Column(name = "AUTHOR") // private String author; // // @Column(name = "COMMENT") // private String comment; // // public Comment() { // // JPA // } // // public Comment(final Long imageId, final String author, final String comment) { // this.imageId = notNull(imageId); // this.author = notBlank(author); // this.comment = notBlank(comment); // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getImageId() { // return imageId; // } // // public void setImageId(Long imageId) { // this.imageId = imageId; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getComment() { // return comment; // } // // public void setComment(String comment) { // this.comment = comment; // } // } // // Path: src/main/java/se/omegapoint/facepalm/infrastructure/event/GenericEvent.java // public class GenericEvent implements ApplicationEvent { // private final Object data; // // public GenericEvent(final Object data) { // this.data = notNull(data); // } // // @Override // public String message() { // return data.toString(); // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // final GenericEvent that = (GenericEvent) o; // return Objects.equals(data, that.data); // } // // @Override // public int hashCode() { // return Objects.hash(data); // } // }
import static java.util.stream.Collectors.toList; import static org.apache.commons.lang3.Validate.notNull; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import se.omegapoint.facepalm.domain.ImageComment; import se.omegapoint.facepalm.domain.event.EventService; import se.omegapoint.facepalm.domain.repository.CommentRepository; import se.omegapoint.facepalm.infrastructure.db.Comment; import se.omegapoint.facepalm.infrastructure.event.GenericEvent; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import java.util.List; import static java.lang.String.format;
/* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.infrastructure; @Repository @Transactional public class JPACommentRepository implements CommentRepository { private final EventService eventService; @PersistenceContext private EntityManager entityManager; @Autowired public JPACommentRepository(final EventService eventService) { this.eventService = notNull(eventService); } @Override public List<ImageComment> findByImageId(final Long id) {
// Path: src/main/java/se/omegapoint/facepalm/domain/ImageComment.java // public class ImageComment { // // public final Long imageId; // public final String author; // public final String text; // // public ImageComment(final Long imageId, final String author, final String text) { // this.imageId = imageId; // this.author = author; // this.text = text; // } // // @Override // public String toString() { // return "ImageComment{" + // "imageId=" + imageId + // ", author='" + author + '\'' + // ", text='" + text + '\'' + // '}'; // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/event/EventService.java // public interface EventService { // void publish(ApplicationEvent event); // } // // Path: src/main/java/se/omegapoint/facepalm/domain/repository/CommentRepository.java // public interface CommentRepository { // List<ImageComment> findByImageId(final Long id); // // void addComment(Long imageId, String author, String text); // } // // Path: src/main/java/se/omegapoint/facepalm/infrastructure/db/Comment.java // @Entity // @Table(name = "COMMENTS") // public class Comment { // @Id // @GeneratedValue // @Column(name = "ID") // private Long id; // // @Column(name = "IMAGE_ID") // private Long imageId; // // @Column(name = "AUTHOR") // private String author; // // @Column(name = "COMMENT") // private String comment; // // public Comment() { // // JPA // } // // public Comment(final Long imageId, final String author, final String comment) { // this.imageId = notNull(imageId); // this.author = notBlank(author); // this.comment = notBlank(comment); // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getImageId() { // return imageId; // } // // public void setImageId(Long imageId) { // this.imageId = imageId; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getComment() { // return comment; // } // // public void setComment(String comment) { // this.comment = comment; // } // } // // Path: src/main/java/se/omegapoint/facepalm/infrastructure/event/GenericEvent.java // public class GenericEvent implements ApplicationEvent { // private final Object data; // // public GenericEvent(final Object data) { // this.data = notNull(data); // } // // @Override // public String message() { // return data.toString(); // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // final GenericEvent that = (GenericEvent) o; // return Objects.equals(data, that.data); // } // // @Override // public int hashCode() { // return Objects.hash(data); // } // } // Path: src/main/java/se/omegapoint/facepalm/infrastructure/JPACommentRepository.java import static java.util.stream.Collectors.toList; import static org.apache.commons.lang3.Validate.notNull; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import se.omegapoint.facepalm.domain.ImageComment; import se.omegapoint.facepalm.domain.event.EventService; import se.omegapoint.facepalm.domain.repository.CommentRepository; import se.omegapoint.facepalm.infrastructure.db.Comment; import se.omegapoint.facepalm.infrastructure.event.GenericEvent; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import java.util.List; import static java.lang.String.format; /* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.infrastructure; @Repository @Transactional public class JPACommentRepository implements CommentRepository { private final EventService eventService; @PersistenceContext private EntityManager entityManager; @Autowired public JPACommentRepository(final EventService eventService) { this.eventService = notNull(eventService); } @Override public List<ImageComment> findByImageId(final Long id) {
eventService.publish(new GenericEvent(format("Searching for image with id[%s]", id)));
Omegapoint/facepalm
src/main/java/se/omegapoint/facepalm/infrastructure/JPACommentRepository.java
// Path: src/main/java/se/omegapoint/facepalm/domain/ImageComment.java // public class ImageComment { // // public final Long imageId; // public final String author; // public final String text; // // public ImageComment(final Long imageId, final String author, final String text) { // this.imageId = imageId; // this.author = author; // this.text = text; // } // // @Override // public String toString() { // return "ImageComment{" + // "imageId=" + imageId + // ", author='" + author + '\'' + // ", text='" + text + '\'' + // '}'; // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/event/EventService.java // public interface EventService { // void publish(ApplicationEvent event); // } // // Path: src/main/java/se/omegapoint/facepalm/domain/repository/CommentRepository.java // public interface CommentRepository { // List<ImageComment> findByImageId(final Long id); // // void addComment(Long imageId, String author, String text); // } // // Path: src/main/java/se/omegapoint/facepalm/infrastructure/db/Comment.java // @Entity // @Table(name = "COMMENTS") // public class Comment { // @Id // @GeneratedValue // @Column(name = "ID") // private Long id; // // @Column(name = "IMAGE_ID") // private Long imageId; // // @Column(name = "AUTHOR") // private String author; // // @Column(name = "COMMENT") // private String comment; // // public Comment() { // // JPA // } // // public Comment(final Long imageId, final String author, final String comment) { // this.imageId = notNull(imageId); // this.author = notBlank(author); // this.comment = notBlank(comment); // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getImageId() { // return imageId; // } // // public void setImageId(Long imageId) { // this.imageId = imageId; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getComment() { // return comment; // } // // public void setComment(String comment) { // this.comment = comment; // } // } // // Path: src/main/java/se/omegapoint/facepalm/infrastructure/event/GenericEvent.java // public class GenericEvent implements ApplicationEvent { // private final Object data; // // public GenericEvent(final Object data) { // this.data = notNull(data); // } // // @Override // public String message() { // return data.toString(); // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // final GenericEvent that = (GenericEvent) o; // return Objects.equals(data, that.data); // } // // @Override // public int hashCode() { // return Objects.hash(data); // } // }
import static java.util.stream.Collectors.toList; import static org.apache.commons.lang3.Validate.notNull; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import se.omegapoint.facepalm.domain.ImageComment; import se.omegapoint.facepalm.domain.event.EventService; import se.omegapoint.facepalm.domain.repository.CommentRepository; import se.omegapoint.facepalm.infrastructure.db.Comment; import se.omegapoint.facepalm.infrastructure.event.GenericEvent; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import java.util.List; import static java.lang.String.format;
/* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.infrastructure; @Repository @Transactional public class JPACommentRepository implements CommentRepository { private final EventService eventService; @PersistenceContext private EntityManager entityManager; @Autowired public JPACommentRepository(final EventService eventService) { this.eventService = notNull(eventService); } @Override public List<ImageComment> findByImageId(final Long id) { eventService.publish(new GenericEvent(format("Searching for image with id[%s]", id)));
// Path: src/main/java/se/omegapoint/facepalm/domain/ImageComment.java // public class ImageComment { // // public final Long imageId; // public final String author; // public final String text; // // public ImageComment(final Long imageId, final String author, final String text) { // this.imageId = imageId; // this.author = author; // this.text = text; // } // // @Override // public String toString() { // return "ImageComment{" + // "imageId=" + imageId + // ", author='" + author + '\'' + // ", text='" + text + '\'' + // '}'; // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/event/EventService.java // public interface EventService { // void publish(ApplicationEvent event); // } // // Path: src/main/java/se/omegapoint/facepalm/domain/repository/CommentRepository.java // public interface CommentRepository { // List<ImageComment> findByImageId(final Long id); // // void addComment(Long imageId, String author, String text); // } // // Path: src/main/java/se/omegapoint/facepalm/infrastructure/db/Comment.java // @Entity // @Table(name = "COMMENTS") // public class Comment { // @Id // @GeneratedValue // @Column(name = "ID") // private Long id; // // @Column(name = "IMAGE_ID") // private Long imageId; // // @Column(name = "AUTHOR") // private String author; // // @Column(name = "COMMENT") // private String comment; // // public Comment() { // // JPA // } // // public Comment(final Long imageId, final String author, final String comment) { // this.imageId = notNull(imageId); // this.author = notBlank(author); // this.comment = notBlank(comment); // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public Long getImageId() { // return imageId; // } // // public void setImageId(Long imageId) { // this.imageId = imageId; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getComment() { // return comment; // } // // public void setComment(String comment) { // this.comment = comment; // } // } // // Path: src/main/java/se/omegapoint/facepalm/infrastructure/event/GenericEvent.java // public class GenericEvent implements ApplicationEvent { // private final Object data; // // public GenericEvent(final Object data) { // this.data = notNull(data); // } // // @Override // public String message() { // return data.toString(); // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // final GenericEvent that = (GenericEvent) o; // return Objects.equals(data, that.data); // } // // @Override // public int hashCode() { // return Objects.hash(data); // } // } // Path: src/main/java/se/omegapoint/facepalm/infrastructure/JPACommentRepository.java import static java.util.stream.Collectors.toList; import static org.apache.commons.lang3.Validate.notNull; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import se.omegapoint.facepalm.domain.ImageComment; import se.omegapoint.facepalm.domain.event.EventService; import se.omegapoint.facepalm.domain.repository.CommentRepository; import se.omegapoint.facepalm.infrastructure.db.Comment; import se.omegapoint.facepalm.infrastructure.event.GenericEvent; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import java.util.List; import static java.lang.String.format; /* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.infrastructure; @Repository @Transactional public class JPACommentRepository implements CommentRepository { private final EventService eventService; @PersistenceContext private EntityManager entityManager; @Autowired public JPACommentRepository(final EventService eventService) { this.eventService = notNull(eventService); } @Override public List<ImageComment> findByImageId(final Long id) { eventService.publish(new GenericEvent(format("Searching for image with id[%s]", id)));
return entityManager.createQuery("SELECT c FROM Comment c WHERE imageId = :id", Comment.class)
Omegapoint/facepalm
src/main/java/se/omegapoint/facepalm/domain/repository/UserRepository.java
// Path: src/main/java/se/omegapoint/facepalm/domain/NewUserCredentials.java // public class NewUserCredentials { // public final String username; // public final String email; // public final String firstname; // public final String lastname; // public final String password; // // public NewUserCredentials(final String username, final String email, final String firstname, final String lastname, final String password) { // this.username = notBlank(username); // this.email = notBlank(email); // this.firstname = notBlank(firstname); // this.lastname = notBlank(lastname); // this.password = notBlank(password); // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // final NewUserCredentials that = (NewUserCredentials) o; // return Objects.equals(username, that.username) && // Objects.equals(email, that.email) && // Objects.equals(firstname, that.firstname) && // Objects.equals(lastname, that.lastname) && // Objects.equals(password, that.password); // } // // @Override // public int hashCode() { // return Objects.hash(username, email, firstname, lastname, password); // } // // @Override // public String toString() { // return "NewUserCredentials{" + // "username='" + username + '\'' + // ", email='" + email + '\'' + // ", firstname='" + firstname + '\'' + // ", lastname='" + lastname + '\'' + // ", password='" + password + '\'' + // '}'; // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/User.java // public class User { // public final String username; // public final String email; // public final String firstname; // public final String lastname; // // /* // Is there a better way than just using strings I wonder? // */ // public User(final String username, final String email, final String firstname, final String lastname) { // this.username = notBlank(username); // this.email = notBlank(email); // this.firstname = notBlank(firstname); // this.lastname = notBlank(lastname); // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // final User user = (User) o; // return Objects.equals(username, user.username) && // Objects.equals(email, user.email) && // Objects.equals(firstname, user.firstname) && // Objects.equals(lastname, user.lastname); // } // // @Override // public int hashCode() { // return Objects.hash(username, email, firstname, lastname); // } // // @Override // public String toString() { // return "User{" + // "username='" + username + '\'' + // ", email='" + email + '\'' + // ", firstname='" + firstname + '\'' + // ", lastname='" + lastname + '\'' + // '}'; // } // }
import se.omegapoint.facepalm.domain.NewUserCredentials; import se.omegapoint.facepalm.domain.User; import java.util.List; import java.util.Optional; import java.util.Set;
/* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.domain.repository; public interface UserRepository { Optional<User> findByUsername(final String username); Set<User> findFriendsFor(String username); Optional<User> findByNameAndPassword(final String username, final String password); List<User> findLike(String value); void addFriend(String user, String friend);
// Path: src/main/java/se/omegapoint/facepalm/domain/NewUserCredentials.java // public class NewUserCredentials { // public final String username; // public final String email; // public final String firstname; // public final String lastname; // public final String password; // // public NewUserCredentials(final String username, final String email, final String firstname, final String lastname, final String password) { // this.username = notBlank(username); // this.email = notBlank(email); // this.firstname = notBlank(firstname); // this.lastname = notBlank(lastname); // this.password = notBlank(password); // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // final NewUserCredentials that = (NewUserCredentials) o; // return Objects.equals(username, that.username) && // Objects.equals(email, that.email) && // Objects.equals(firstname, that.firstname) && // Objects.equals(lastname, that.lastname) && // Objects.equals(password, that.password); // } // // @Override // public int hashCode() { // return Objects.hash(username, email, firstname, lastname, password); // } // // @Override // public String toString() { // return "NewUserCredentials{" + // "username='" + username + '\'' + // ", email='" + email + '\'' + // ", firstname='" + firstname + '\'' + // ", lastname='" + lastname + '\'' + // ", password='" + password + '\'' + // '}'; // } // } // // Path: src/main/java/se/omegapoint/facepalm/domain/User.java // public class User { // public final String username; // public final String email; // public final String firstname; // public final String lastname; // // /* // Is there a better way than just using strings I wonder? // */ // public User(final String username, final String email, final String firstname, final String lastname) { // this.username = notBlank(username); // this.email = notBlank(email); // this.firstname = notBlank(firstname); // this.lastname = notBlank(lastname); // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // final User user = (User) o; // return Objects.equals(username, user.username) && // Objects.equals(email, user.email) && // Objects.equals(firstname, user.firstname) && // Objects.equals(lastname, user.lastname); // } // // @Override // public int hashCode() { // return Objects.hash(username, email, firstname, lastname); // } // // @Override // public String toString() { // return "User{" + // "username='" + username + '\'' + // ", email='" + email + '\'' + // ", firstname='" + firstname + '\'' + // ", lastname='" + lastname + '\'' + // '}'; // } // } // Path: src/main/java/se/omegapoint/facepalm/domain/repository/UserRepository.java import se.omegapoint.facepalm.domain.NewUserCredentials; import se.omegapoint.facepalm.domain.User; import java.util.List; import java.util.Optional; import java.util.Set; /* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.domain.repository; public interface UserRepository { Optional<User> findByUsername(final String username); Set<User> findFriendsFor(String username); Optional<User> findByNameAndPassword(final String username, final String password); List<User> findLike(String value); void addFriend(String user, String friend);
void addUser(NewUserCredentials credentials);
Omegapoint/facepalm
src/main/java/se/omegapoint/facepalm/client/adapters/DocumentAdapter.java
// Path: src/main/java/se/omegapoint/facepalm/application/DocumentService.java // @Service // public class DocumentService { // private DocumentRepository documentRepository; // // @Autowired // public DocumentService(final DocumentRepository documentRepository) { // this.documentRepository = notNull(documentRepository); // } // // public List<Document> documentsForUser(final String user) { // notBlank(user); // // return documentRepository.findAllFor(user); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/Document.java // public class Document { // public final String filename; // public final Long fileSize; // public final String date; // // public Document(final String filename, final Long fileSize, final String date) { // this.filename = filename; // this.fileSize = fileSize; // this.date = date; // } // }
import org.springframework.beans.factory.annotation.Autowired; import se.omegapoint.facepalm.application.DocumentService; import se.omegapoint.facepalm.client.config.Adapter; import se.omegapoint.facepalm.client.models.Document; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.List; import static java.util.stream.Collectors.toList; import static org.apache.commons.lang3.Validate.notBlank; import static org.apache.commons.lang3.Validate.notNull;
/* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.client.adapters; @Adapter public class DocumentAdapter {
// Path: src/main/java/se/omegapoint/facepalm/application/DocumentService.java // @Service // public class DocumentService { // private DocumentRepository documentRepository; // // @Autowired // public DocumentService(final DocumentRepository documentRepository) { // this.documentRepository = notNull(documentRepository); // } // // public List<Document> documentsForUser(final String user) { // notBlank(user); // // return documentRepository.findAllFor(user); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/Document.java // public class Document { // public final String filename; // public final Long fileSize; // public final String date; // // public Document(final String filename, final Long fileSize, final String date) { // this.filename = filename; // this.fileSize = fileSize; // this.date = date; // } // } // Path: src/main/java/se/omegapoint/facepalm/client/adapters/DocumentAdapter.java import org.springframework.beans.factory.annotation.Autowired; import se.omegapoint.facepalm.application.DocumentService; import se.omegapoint.facepalm.client.config.Adapter; import se.omegapoint.facepalm.client.models.Document; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.List; import static java.util.stream.Collectors.toList; import static org.apache.commons.lang3.Validate.notBlank; import static org.apache.commons.lang3.Validate.notNull; /* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.client.adapters; @Adapter public class DocumentAdapter {
private DocumentService documentService;
Omegapoint/facepalm
src/main/java/se/omegapoint/facepalm/client/adapters/DocumentAdapter.java
// Path: src/main/java/se/omegapoint/facepalm/application/DocumentService.java // @Service // public class DocumentService { // private DocumentRepository documentRepository; // // @Autowired // public DocumentService(final DocumentRepository documentRepository) { // this.documentRepository = notNull(documentRepository); // } // // public List<Document> documentsForUser(final String user) { // notBlank(user); // // return documentRepository.findAllFor(user); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/Document.java // public class Document { // public final String filename; // public final Long fileSize; // public final String date; // // public Document(final String filename, final Long fileSize, final String date) { // this.filename = filename; // this.fileSize = fileSize; // this.date = date; // } // }
import org.springframework.beans.factory.annotation.Autowired; import se.omegapoint.facepalm.application.DocumentService; import se.omegapoint.facepalm.client.config.Adapter; import se.omegapoint.facepalm.client.models.Document; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.List; import static java.util.stream.Collectors.toList; import static org.apache.commons.lang3.Validate.notBlank; import static org.apache.commons.lang3.Validate.notNull;
/* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.client.adapters; @Adapter public class DocumentAdapter { private DocumentService documentService; @Autowired public DocumentAdapter(final DocumentService documentService) { this.documentService = notNull(documentService); }
// Path: src/main/java/se/omegapoint/facepalm/application/DocumentService.java // @Service // public class DocumentService { // private DocumentRepository documentRepository; // // @Autowired // public DocumentService(final DocumentRepository documentRepository) { // this.documentRepository = notNull(documentRepository); // } // // public List<Document> documentsForUser(final String user) { // notBlank(user); // // return documentRepository.findAllFor(user); // } // } // // Path: src/main/java/se/omegapoint/facepalm/client/models/Document.java // public class Document { // public final String filename; // public final Long fileSize; // public final String date; // // public Document(final String filename, final Long fileSize, final String date) { // this.filename = filename; // this.fileSize = fileSize; // this.date = date; // } // } // Path: src/main/java/se/omegapoint/facepalm/client/adapters/DocumentAdapter.java import org.springframework.beans.factory.annotation.Autowired; import se.omegapoint.facepalm.application.DocumentService; import se.omegapoint.facepalm.client.config.Adapter; import se.omegapoint.facepalm.client.models.Document; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.List; import static java.util.stream.Collectors.toList; import static org.apache.commons.lang3.Validate.notBlank; import static org.apache.commons.lang3.Validate.notNull; /* * Copyright 2016 the original author or authors. * * 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 se.omegapoint.facepalm.client.adapters; @Adapter public class DocumentAdapter { private DocumentService documentService; @Autowired public DocumentAdapter(final DocumentService documentService) { this.documentService = notNull(documentService); }
public List<Document> documentsFor(final String user) {
ZevenFang/zevencourse
src/main/java/com/zeven/course/action/TeacherAction.java
// Path: src/main/java/com/zeven/course/util/Auth.java // public class Auth { // // public static final Key key = MacProvider.generateKey(); // public static final long expire = 7200000; //2 hours // // public static void main (String [] args) { // Map<String,Object> claims = new HashMap<String, Object>(); // claims.put("id",1); // claims.put("name","zeven"); // claims.put("role","admin"); // String s = Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.HS512, key).compact(); // System.out.println(s); // Claims result; // try { // result = Jwts.parser().setSigningKey(key).parseClaimsJws(s).getBody(); // System.out.println(result.get("id")+"|"+result.get("name")+"|"+result.get("role")); // } catch (SignatureException e){ // System.out.println("401 No Authentication"); // } // } // } // // Path: src/main/java/com/zeven/course/util/Message.java // public class Message { // private int code; // private String msg; // private Object data = ""; // // public Message() { // } // // public Message(int code, String msg) { // this.code = code; // this.msg = msg; // } // // public Message(int code, String msg, Object data) { // this.code = code; // this.msg = msg; // this.data = data; // } // // public int getCode() { // return code; // } // // public void setCode(int code) { // this.code = code; // } // // public String getMsg() { // return msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // // public Object getData() { // return data; // } // // public void setData(Object data) { // this.data = data; // } // } // // Path: src/main/java/com/zeven/course/util/Token.java // public class Token { // // private int id; // private String name; // private String role; // private int err = 0; // public static final int ExpiredJwtError = 1; // public static final int SignatureError = 2; // // public Token(String token) { // try { // Claims claims = Jwts.parser().setSigningKey(Auth.key).parseClaimsJws(token).getBody(); // this.id = Integer.parseInt(claims.get("id").toString()); // this.name = claims.get("name").toString(); // this.role = claims.get("role").toString(); // } catch (ExpiredJwtException e){ // this.err = ExpiredJwtError; // } catch (SignatureException e) { // this.err = SignatureError; // } // // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public String getRole() { // return role; // } // // public int getErr() { // return err; // } // // }
import com.zeven.course.service.*; import com.zeven.course.util.Auth; import com.zeven.course.util.Message; import com.zeven.course.util.Token; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource;
package com.zeven.course.action; /** * Created by fangf on 2016/5/22. */ @RequestMapping("/Teacher") @Controller public class TeacherAction { @Resource private CourseService courseService; @Resource private StudentService studentService; @Resource private TeacherCourseService tcService; @Resource private ClassService classService; @Resource private CourseStudentService csService; @ResponseBody @RequestMapping("/course/getAll")
// Path: src/main/java/com/zeven/course/util/Auth.java // public class Auth { // // public static final Key key = MacProvider.generateKey(); // public static final long expire = 7200000; //2 hours // // public static void main (String [] args) { // Map<String,Object> claims = new HashMap<String, Object>(); // claims.put("id",1); // claims.put("name","zeven"); // claims.put("role","admin"); // String s = Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.HS512, key).compact(); // System.out.println(s); // Claims result; // try { // result = Jwts.parser().setSigningKey(key).parseClaimsJws(s).getBody(); // System.out.println(result.get("id")+"|"+result.get("name")+"|"+result.get("role")); // } catch (SignatureException e){ // System.out.println("401 No Authentication"); // } // } // } // // Path: src/main/java/com/zeven/course/util/Message.java // public class Message { // private int code; // private String msg; // private Object data = ""; // // public Message() { // } // // public Message(int code, String msg) { // this.code = code; // this.msg = msg; // } // // public Message(int code, String msg, Object data) { // this.code = code; // this.msg = msg; // this.data = data; // } // // public int getCode() { // return code; // } // // public void setCode(int code) { // this.code = code; // } // // public String getMsg() { // return msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // // public Object getData() { // return data; // } // // public void setData(Object data) { // this.data = data; // } // } // // Path: src/main/java/com/zeven/course/util/Token.java // public class Token { // // private int id; // private String name; // private String role; // private int err = 0; // public static final int ExpiredJwtError = 1; // public static final int SignatureError = 2; // // public Token(String token) { // try { // Claims claims = Jwts.parser().setSigningKey(Auth.key).parseClaimsJws(token).getBody(); // this.id = Integer.parseInt(claims.get("id").toString()); // this.name = claims.get("name").toString(); // this.role = claims.get("role").toString(); // } catch (ExpiredJwtException e){ // this.err = ExpiredJwtError; // } catch (SignatureException e) { // this.err = SignatureError; // } // // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public String getRole() { // return role; // } // // public int getErr() { // return err; // } // // } // Path: src/main/java/com/zeven/course/action/TeacherAction.java import com.zeven.course.service.*; import com.zeven.course.util.Auth; import com.zeven.course.util.Message; import com.zeven.course.util.Token; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; package com.zeven.course.action; /** * Created by fangf on 2016/5/22. */ @RequestMapping("/Teacher") @Controller public class TeacherAction { @Resource private CourseService courseService; @Resource private StudentService studentService; @Resource private TeacherCourseService tcService; @Resource private ClassService classService; @Resource private CourseStudentService csService; @ResponseBody @RequestMapping("/course/getAll")
public Message getAllCourse(){
ZevenFang/zevencourse
src/main/java/com/zeven/course/action/TeacherAction.java
// Path: src/main/java/com/zeven/course/util/Auth.java // public class Auth { // // public static final Key key = MacProvider.generateKey(); // public static final long expire = 7200000; //2 hours // // public static void main (String [] args) { // Map<String,Object> claims = new HashMap<String, Object>(); // claims.put("id",1); // claims.put("name","zeven"); // claims.put("role","admin"); // String s = Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.HS512, key).compact(); // System.out.println(s); // Claims result; // try { // result = Jwts.parser().setSigningKey(key).parseClaimsJws(s).getBody(); // System.out.println(result.get("id")+"|"+result.get("name")+"|"+result.get("role")); // } catch (SignatureException e){ // System.out.println("401 No Authentication"); // } // } // } // // Path: src/main/java/com/zeven/course/util/Message.java // public class Message { // private int code; // private String msg; // private Object data = ""; // // public Message() { // } // // public Message(int code, String msg) { // this.code = code; // this.msg = msg; // } // // public Message(int code, String msg, Object data) { // this.code = code; // this.msg = msg; // this.data = data; // } // // public int getCode() { // return code; // } // // public void setCode(int code) { // this.code = code; // } // // public String getMsg() { // return msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // // public Object getData() { // return data; // } // // public void setData(Object data) { // this.data = data; // } // } // // Path: src/main/java/com/zeven/course/util/Token.java // public class Token { // // private int id; // private String name; // private String role; // private int err = 0; // public static final int ExpiredJwtError = 1; // public static final int SignatureError = 2; // // public Token(String token) { // try { // Claims claims = Jwts.parser().setSigningKey(Auth.key).parseClaimsJws(token).getBody(); // this.id = Integer.parseInt(claims.get("id").toString()); // this.name = claims.get("name").toString(); // this.role = claims.get("role").toString(); // } catch (ExpiredJwtException e){ // this.err = ExpiredJwtError; // } catch (SignatureException e) { // this.err = SignatureError; // } // // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public String getRole() { // return role; // } // // public int getErr() { // return err; // } // // }
import com.zeven.course.service.*; import com.zeven.course.util.Auth; import com.zeven.course.util.Message; import com.zeven.course.util.Token; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource;
package com.zeven.course.action; /** * Created by fangf on 2016/5/22. */ @RequestMapping("/Teacher") @Controller public class TeacherAction { @Resource private CourseService courseService; @Resource private StudentService studentService; @Resource private TeacherCourseService tcService; @Resource private ClassService classService; @Resource private CourseStudentService csService; @ResponseBody @RequestMapping("/course/getAll") public Message getAllCourse(){ return new Message(1,"ok",courseService.getAvailableCourses()); } @ResponseBody @RequestMapping("/course/selectCourses") public Message selectCourses(@RequestParam("ids[]") Integer[] ids, @RequestHeader("Authorization") String token){
// Path: src/main/java/com/zeven/course/util/Auth.java // public class Auth { // // public static final Key key = MacProvider.generateKey(); // public static final long expire = 7200000; //2 hours // // public static void main (String [] args) { // Map<String,Object> claims = new HashMap<String, Object>(); // claims.put("id",1); // claims.put("name","zeven"); // claims.put("role","admin"); // String s = Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.HS512, key).compact(); // System.out.println(s); // Claims result; // try { // result = Jwts.parser().setSigningKey(key).parseClaimsJws(s).getBody(); // System.out.println(result.get("id")+"|"+result.get("name")+"|"+result.get("role")); // } catch (SignatureException e){ // System.out.println("401 No Authentication"); // } // } // } // // Path: src/main/java/com/zeven/course/util/Message.java // public class Message { // private int code; // private String msg; // private Object data = ""; // // public Message() { // } // // public Message(int code, String msg) { // this.code = code; // this.msg = msg; // } // // public Message(int code, String msg, Object data) { // this.code = code; // this.msg = msg; // this.data = data; // } // // public int getCode() { // return code; // } // // public void setCode(int code) { // this.code = code; // } // // public String getMsg() { // return msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // // public Object getData() { // return data; // } // // public void setData(Object data) { // this.data = data; // } // } // // Path: src/main/java/com/zeven/course/util/Token.java // public class Token { // // private int id; // private String name; // private String role; // private int err = 0; // public static final int ExpiredJwtError = 1; // public static final int SignatureError = 2; // // public Token(String token) { // try { // Claims claims = Jwts.parser().setSigningKey(Auth.key).parseClaimsJws(token).getBody(); // this.id = Integer.parseInt(claims.get("id").toString()); // this.name = claims.get("name").toString(); // this.role = claims.get("role").toString(); // } catch (ExpiredJwtException e){ // this.err = ExpiredJwtError; // } catch (SignatureException e) { // this.err = SignatureError; // } // // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public String getRole() { // return role; // } // // public int getErr() { // return err; // } // // } // Path: src/main/java/com/zeven/course/action/TeacherAction.java import com.zeven.course.service.*; import com.zeven.course.util.Auth; import com.zeven.course.util.Message; import com.zeven.course.util.Token; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; package com.zeven.course.action; /** * Created by fangf on 2016/5/22. */ @RequestMapping("/Teacher") @Controller public class TeacherAction { @Resource private CourseService courseService; @Resource private StudentService studentService; @Resource private TeacherCourseService tcService; @Resource private ClassService classService; @Resource private CourseStudentService csService; @ResponseBody @RequestMapping("/course/getAll") public Message getAllCourse(){ return new Message(1,"ok",courseService.getAvailableCourses()); } @ResponseBody @RequestMapping("/course/selectCourses") public Message selectCourses(@RequestParam("ids[]") Integer[] ids, @RequestHeader("Authorization") String token){
int userID = new Token(token).getId();
ZevenFang/zevencourse
src/main/java/com/zeven/course/interceptor/AccessInterceptor.java
// Path: src/main/java/com/zeven/course/util/Token.java // public class Token { // // private int id; // private String name; // private String role; // private int err = 0; // public static final int ExpiredJwtError = 1; // public static final int SignatureError = 2; // // public Token(String token) { // try { // Claims claims = Jwts.parser().setSigningKey(Auth.key).parseClaimsJws(token).getBody(); // this.id = Integer.parseInt(claims.get("id").toString()); // this.name = claims.get("name").toString(); // this.role = claims.get("role").toString(); // } catch (ExpiredJwtException e){ // this.err = ExpiredJwtError; // } catch (SignatureException e) { // this.err = SignatureError; // } // // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public String getRole() { // return role; // } // // public int getErr() { // return err; // } // // }
import com.zeven.course.util.Token; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
package com.zeven.course.interceptor; /** * Created by fangf on 2016/5/21. * OAuth权限认证 */ public class AccessInterceptor extends CrossDomainInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String path = request.getContextPath(); String uri = request.getRequestURI(); if (!uri.startsWith(path+"/Access")) { String auth = request.getHeader("Authorization"); if (auth==null){ response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authentication Failed: Require Authorization"); return false; }
// Path: src/main/java/com/zeven/course/util/Token.java // public class Token { // // private int id; // private String name; // private String role; // private int err = 0; // public static final int ExpiredJwtError = 1; // public static final int SignatureError = 2; // // public Token(String token) { // try { // Claims claims = Jwts.parser().setSigningKey(Auth.key).parseClaimsJws(token).getBody(); // this.id = Integer.parseInt(claims.get("id").toString()); // this.name = claims.get("name").toString(); // this.role = claims.get("role").toString(); // } catch (ExpiredJwtException e){ // this.err = ExpiredJwtError; // } catch (SignatureException e) { // this.err = SignatureError; // } // // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public String getRole() { // return role; // } // // public int getErr() { // return err; // } // // } // Path: src/main/java/com/zeven/course/interceptor/AccessInterceptor.java import com.zeven.course.util.Token; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; package com.zeven.course.interceptor; /** * Created by fangf on 2016/5/21. * OAuth权限认证 */ public class AccessInterceptor extends CrossDomainInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String path = request.getContextPath(); String uri = request.getRequestURI(); if (!uri.startsWith(path+"/Access")) { String auth = request.getHeader("Authorization"); if (auth==null){ response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authentication Failed: Require Authorization"); return false; }
Token token = new Token(auth);
ZevenFang/zevencourse
src/main/java/com/zeven/course/action/DeptManageAction.java
// Path: src/main/java/com/zeven/course/model/Dept.java // @Entity // public class Dept { // private int id; // private String name; // private String description; // // @Id // @Column(name = "id", nullable = false) // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // @Basic // @Column(name = "name", nullable = false, length = 45) // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Basic // @Column(name = "description", nullable = true, length = 255) // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Dept dept = (Dept) o; // // if (id != dept.id) return false; // if (name != null ? !name.equals(dept.name) : dept.name != null) return false; // if (description != null ? !description.equals(dept.description) : dept.description != null) return false; // // return true; // } // // @Override // public int hashCode() { // int result = id; // result = 31 * result + (name != null ? name.hashCode() : 0); // result = 31 * result + (description != null ? description.hashCode() : 0); // return result; // } // } // // Path: src/main/java/com/zeven/course/service/DeptService.java // @Component // public class DeptService extends DaoSupportImpl<Dept> { // // } // // Path: src/main/java/com/zeven/course/util/Message.java // public class Message { // private int code; // private String msg; // private Object data = ""; // // public Message() { // } // // public Message(int code, String msg) { // this.code = code; // this.msg = msg; // } // // public Message(int code, String msg, Object data) { // this.code = code; // this.msg = msg; // this.data = data; // } // // public int getCode() { // return code; // } // // public void setCode(int code) { // this.code = code; // } // // public String getMsg() { // return msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // // public Object getData() { // return data; // } // // public void setData(Object data) { // this.data = data; // } // }
import com.zeven.course.model.Dept; import com.zeven.course.service.DeptService; import com.zeven.course.util.Message; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; import java.util.List;
package com.zeven.course.action; /** * Created by fangf on 2016/5/19. */ @RequestMapping("/Admin/dept") @Controller public class DeptManageAction { @Resource
// Path: src/main/java/com/zeven/course/model/Dept.java // @Entity // public class Dept { // private int id; // private String name; // private String description; // // @Id // @Column(name = "id", nullable = false) // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // @Basic // @Column(name = "name", nullable = false, length = 45) // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Basic // @Column(name = "description", nullable = true, length = 255) // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Dept dept = (Dept) o; // // if (id != dept.id) return false; // if (name != null ? !name.equals(dept.name) : dept.name != null) return false; // if (description != null ? !description.equals(dept.description) : dept.description != null) return false; // // return true; // } // // @Override // public int hashCode() { // int result = id; // result = 31 * result + (name != null ? name.hashCode() : 0); // result = 31 * result + (description != null ? description.hashCode() : 0); // return result; // } // } // // Path: src/main/java/com/zeven/course/service/DeptService.java // @Component // public class DeptService extends DaoSupportImpl<Dept> { // // } // // Path: src/main/java/com/zeven/course/util/Message.java // public class Message { // private int code; // private String msg; // private Object data = ""; // // public Message() { // } // // public Message(int code, String msg) { // this.code = code; // this.msg = msg; // } // // public Message(int code, String msg, Object data) { // this.code = code; // this.msg = msg; // this.data = data; // } // // public int getCode() { // return code; // } // // public void setCode(int code) { // this.code = code; // } // // public String getMsg() { // return msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // // public Object getData() { // return data; // } // // public void setData(Object data) { // this.data = data; // } // } // Path: src/main/java/com/zeven/course/action/DeptManageAction.java import com.zeven.course.model.Dept; import com.zeven.course.service.DeptService; import com.zeven.course.util.Message; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; import java.util.List; package com.zeven.course.action; /** * Created by fangf on 2016/5/19. */ @RequestMapping("/Admin/dept") @Controller public class DeptManageAction { @Resource
private DeptService service;
ZevenFang/zevencourse
src/main/java/com/zeven/course/action/DeptManageAction.java
// Path: src/main/java/com/zeven/course/model/Dept.java // @Entity // public class Dept { // private int id; // private String name; // private String description; // // @Id // @Column(name = "id", nullable = false) // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // @Basic // @Column(name = "name", nullable = false, length = 45) // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Basic // @Column(name = "description", nullable = true, length = 255) // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Dept dept = (Dept) o; // // if (id != dept.id) return false; // if (name != null ? !name.equals(dept.name) : dept.name != null) return false; // if (description != null ? !description.equals(dept.description) : dept.description != null) return false; // // return true; // } // // @Override // public int hashCode() { // int result = id; // result = 31 * result + (name != null ? name.hashCode() : 0); // result = 31 * result + (description != null ? description.hashCode() : 0); // return result; // } // } // // Path: src/main/java/com/zeven/course/service/DeptService.java // @Component // public class DeptService extends DaoSupportImpl<Dept> { // // } // // Path: src/main/java/com/zeven/course/util/Message.java // public class Message { // private int code; // private String msg; // private Object data = ""; // // public Message() { // } // // public Message(int code, String msg) { // this.code = code; // this.msg = msg; // } // // public Message(int code, String msg, Object data) { // this.code = code; // this.msg = msg; // this.data = data; // } // // public int getCode() { // return code; // } // // public void setCode(int code) { // this.code = code; // } // // public String getMsg() { // return msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // // public Object getData() { // return data; // } // // public void setData(Object data) { // this.data = data; // } // }
import com.zeven.course.model.Dept; import com.zeven.course.service.DeptService; import com.zeven.course.util.Message; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; import java.util.List;
package com.zeven.course.action; /** * Created by fangf on 2016/5/19. */ @RequestMapping("/Admin/dept") @Controller public class DeptManageAction { @Resource private DeptService service; @ResponseBody @RequestMapping("/getAll")
// Path: src/main/java/com/zeven/course/model/Dept.java // @Entity // public class Dept { // private int id; // private String name; // private String description; // // @Id // @Column(name = "id", nullable = false) // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // @Basic // @Column(name = "name", nullable = false, length = 45) // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Basic // @Column(name = "description", nullable = true, length = 255) // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Dept dept = (Dept) o; // // if (id != dept.id) return false; // if (name != null ? !name.equals(dept.name) : dept.name != null) return false; // if (description != null ? !description.equals(dept.description) : dept.description != null) return false; // // return true; // } // // @Override // public int hashCode() { // int result = id; // result = 31 * result + (name != null ? name.hashCode() : 0); // result = 31 * result + (description != null ? description.hashCode() : 0); // return result; // } // } // // Path: src/main/java/com/zeven/course/service/DeptService.java // @Component // public class DeptService extends DaoSupportImpl<Dept> { // // } // // Path: src/main/java/com/zeven/course/util/Message.java // public class Message { // private int code; // private String msg; // private Object data = ""; // // public Message() { // } // // public Message(int code, String msg) { // this.code = code; // this.msg = msg; // } // // public Message(int code, String msg, Object data) { // this.code = code; // this.msg = msg; // this.data = data; // } // // public int getCode() { // return code; // } // // public void setCode(int code) { // this.code = code; // } // // public String getMsg() { // return msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // // public Object getData() { // return data; // } // // public void setData(Object data) { // this.data = data; // } // } // Path: src/main/java/com/zeven/course/action/DeptManageAction.java import com.zeven.course.model.Dept; import com.zeven.course.service.DeptService; import com.zeven.course.util.Message; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; import java.util.List; package com.zeven.course.action; /** * Created by fangf on 2016/5/19. */ @RequestMapping("/Admin/dept") @Controller public class DeptManageAction { @Resource private DeptService service; @ResponseBody @RequestMapping("/getAll")
public Message getAll(){
ZevenFang/zevencourse
src/main/java/com/zeven/course/action/DeptManageAction.java
// Path: src/main/java/com/zeven/course/model/Dept.java // @Entity // public class Dept { // private int id; // private String name; // private String description; // // @Id // @Column(name = "id", nullable = false) // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // @Basic // @Column(name = "name", nullable = false, length = 45) // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Basic // @Column(name = "description", nullable = true, length = 255) // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Dept dept = (Dept) o; // // if (id != dept.id) return false; // if (name != null ? !name.equals(dept.name) : dept.name != null) return false; // if (description != null ? !description.equals(dept.description) : dept.description != null) return false; // // return true; // } // // @Override // public int hashCode() { // int result = id; // result = 31 * result + (name != null ? name.hashCode() : 0); // result = 31 * result + (description != null ? description.hashCode() : 0); // return result; // } // } // // Path: src/main/java/com/zeven/course/service/DeptService.java // @Component // public class DeptService extends DaoSupportImpl<Dept> { // // } // // Path: src/main/java/com/zeven/course/util/Message.java // public class Message { // private int code; // private String msg; // private Object data = ""; // // public Message() { // } // // public Message(int code, String msg) { // this.code = code; // this.msg = msg; // } // // public Message(int code, String msg, Object data) { // this.code = code; // this.msg = msg; // this.data = data; // } // // public int getCode() { // return code; // } // // public void setCode(int code) { // this.code = code; // } // // public String getMsg() { // return msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // // public Object getData() { // return data; // } // // public void setData(Object data) { // this.data = data; // } // }
import com.zeven.course.model.Dept; import com.zeven.course.service.DeptService; import com.zeven.course.util.Message; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; import java.util.List;
package com.zeven.course.action; /** * Created by fangf on 2016/5/19. */ @RequestMapping("/Admin/dept") @Controller public class DeptManageAction { @Resource private DeptService service; @ResponseBody @RequestMapping("/getAll") public Message getAll(){ Message msg = new Message(1,"ok"); msg.setData(service.findAll()); return msg; } @ResponseBody @RequestMapping("/add") public Message add(@RequestParam String name, String description){ if (service.isFieldExisted("name",name)) return new Message(-1,"已存在“"+name+"”");
// Path: src/main/java/com/zeven/course/model/Dept.java // @Entity // public class Dept { // private int id; // private String name; // private String description; // // @Id // @Column(name = "id", nullable = false) // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // @Basic // @Column(name = "name", nullable = false, length = 45) // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Basic // @Column(name = "description", nullable = true, length = 255) // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Dept dept = (Dept) o; // // if (id != dept.id) return false; // if (name != null ? !name.equals(dept.name) : dept.name != null) return false; // if (description != null ? !description.equals(dept.description) : dept.description != null) return false; // // return true; // } // // @Override // public int hashCode() { // int result = id; // result = 31 * result + (name != null ? name.hashCode() : 0); // result = 31 * result + (description != null ? description.hashCode() : 0); // return result; // } // } // // Path: src/main/java/com/zeven/course/service/DeptService.java // @Component // public class DeptService extends DaoSupportImpl<Dept> { // // } // // Path: src/main/java/com/zeven/course/util/Message.java // public class Message { // private int code; // private String msg; // private Object data = ""; // // public Message() { // } // // public Message(int code, String msg) { // this.code = code; // this.msg = msg; // } // // public Message(int code, String msg, Object data) { // this.code = code; // this.msg = msg; // this.data = data; // } // // public int getCode() { // return code; // } // // public void setCode(int code) { // this.code = code; // } // // public String getMsg() { // return msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // // public Object getData() { // return data; // } // // public void setData(Object data) { // this.data = data; // } // } // Path: src/main/java/com/zeven/course/action/DeptManageAction.java import com.zeven.course.model.Dept; import com.zeven.course.service.DeptService; import com.zeven.course.util.Message; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; import java.util.List; package com.zeven.course.action; /** * Created by fangf on 2016/5/19. */ @RequestMapping("/Admin/dept") @Controller public class DeptManageAction { @Resource private DeptService service; @ResponseBody @RequestMapping("/getAll") public Message getAll(){ Message msg = new Message(1,"ok"); msg.setData(service.findAll()); return msg; } @ResponseBody @RequestMapping("/add") public Message add(@RequestParam String name, String description){ if (service.isFieldExisted("name",name)) return new Message(-1,"已存在“"+name+"”");
Dept dept = new Dept();
ZevenFang/zevencourse
src/main/java/com/zeven/course/action/ClassManageAction.java
// Path: src/main/java/com/zeven/course/model/Clazz.java // @Entity // public class Clazz { // private int id; // private String name; // private int deptId; // // @Id // @Column(name = "id", nullable = false) // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // @Basic // @Column(name = "name", nullable = false, length = 45) // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Basic // @Column(name = "dept_id", nullable = false) // public int getDeptId() { // return deptId; // } // // public void setDeptId(int deptId) { // this.deptId = deptId; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Clazz clazz = (Clazz) o; // // if (id != clazz.id) return false; // if (deptId != clazz.deptId) return false; // if (name != null ? !name.equals(clazz.name) : clazz.name != null) return false; // // return true; // } // // @Override // public int hashCode() { // int result = id; // result = 31 * result + (name != null ? name.hashCode() : 0); // result = 31 * result + deptId; // return result; // } // } // // Path: src/main/java/com/zeven/course/service/ClassService.java // @Component // public class ClassService extends DaoSupportImpl<Clazz> { // // } // // Path: src/main/java/com/zeven/course/util/Message.java // public class Message { // private int code; // private String msg; // private Object data = ""; // // public Message() { // } // // public Message(int code, String msg) { // this.code = code; // this.msg = msg; // } // // public Message(int code, String msg, Object data) { // this.code = code; // this.msg = msg; // this.data = data; // } // // public int getCode() { // return code; // } // // public void setCode(int code) { // this.code = code; // } // // public String getMsg() { // return msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // // public Object getData() { // return data; // } // // public void setData(Object data) { // this.data = data; // } // }
import com.zeven.course.model.Clazz; import com.zeven.course.service.ClassService; import com.zeven.course.util.Message; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import javax.annotation.Resource;
package com.zeven.course.action; /** * Created by fangf on 2016/5/20. */ @RequestMapping("/Admin/class") @Controller public class ClassManageAction { @Resource
// Path: src/main/java/com/zeven/course/model/Clazz.java // @Entity // public class Clazz { // private int id; // private String name; // private int deptId; // // @Id // @Column(name = "id", nullable = false) // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // @Basic // @Column(name = "name", nullable = false, length = 45) // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Basic // @Column(name = "dept_id", nullable = false) // public int getDeptId() { // return deptId; // } // // public void setDeptId(int deptId) { // this.deptId = deptId; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Clazz clazz = (Clazz) o; // // if (id != clazz.id) return false; // if (deptId != clazz.deptId) return false; // if (name != null ? !name.equals(clazz.name) : clazz.name != null) return false; // // return true; // } // // @Override // public int hashCode() { // int result = id; // result = 31 * result + (name != null ? name.hashCode() : 0); // result = 31 * result + deptId; // return result; // } // } // // Path: src/main/java/com/zeven/course/service/ClassService.java // @Component // public class ClassService extends DaoSupportImpl<Clazz> { // // } // // Path: src/main/java/com/zeven/course/util/Message.java // public class Message { // private int code; // private String msg; // private Object data = ""; // // public Message() { // } // // public Message(int code, String msg) { // this.code = code; // this.msg = msg; // } // // public Message(int code, String msg, Object data) { // this.code = code; // this.msg = msg; // this.data = data; // } // // public int getCode() { // return code; // } // // public void setCode(int code) { // this.code = code; // } // // public String getMsg() { // return msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // // public Object getData() { // return data; // } // // public void setData(Object data) { // this.data = data; // } // } // Path: src/main/java/com/zeven/course/action/ClassManageAction.java import com.zeven.course.model.Clazz; import com.zeven.course.service.ClassService; import com.zeven.course.util.Message; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import javax.annotation.Resource; package com.zeven.course.action; /** * Created by fangf on 2016/5/20. */ @RequestMapping("/Admin/class") @Controller public class ClassManageAction { @Resource
private ClassService service;
ZevenFang/zevencourse
src/main/java/com/zeven/course/action/ClassManageAction.java
// Path: src/main/java/com/zeven/course/model/Clazz.java // @Entity // public class Clazz { // private int id; // private String name; // private int deptId; // // @Id // @Column(name = "id", nullable = false) // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // @Basic // @Column(name = "name", nullable = false, length = 45) // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Basic // @Column(name = "dept_id", nullable = false) // public int getDeptId() { // return deptId; // } // // public void setDeptId(int deptId) { // this.deptId = deptId; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Clazz clazz = (Clazz) o; // // if (id != clazz.id) return false; // if (deptId != clazz.deptId) return false; // if (name != null ? !name.equals(clazz.name) : clazz.name != null) return false; // // return true; // } // // @Override // public int hashCode() { // int result = id; // result = 31 * result + (name != null ? name.hashCode() : 0); // result = 31 * result + deptId; // return result; // } // } // // Path: src/main/java/com/zeven/course/service/ClassService.java // @Component // public class ClassService extends DaoSupportImpl<Clazz> { // // } // // Path: src/main/java/com/zeven/course/util/Message.java // public class Message { // private int code; // private String msg; // private Object data = ""; // // public Message() { // } // // public Message(int code, String msg) { // this.code = code; // this.msg = msg; // } // // public Message(int code, String msg, Object data) { // this.code = code; // this.msg = msg; // this.data = data; // } // // public int getCode() { // return code; // } // // public void setCode(int code) { // this.code = code; // } // // public String getMsg() { // return msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // // public Object getData() { // return data; // } // // public void setData(Object data) { // this.data = data; // } // }
import com.zeven.course.model.Clazz; import com.zeven.course.service.ClassService; import com.zeven.course.util.Message; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import javax.annotation.Resource;
package com.zeven.course.action; /** * Created by fangf on 2016/5/20. */ @RequestMapping("/Admin/class") @Controller public class ClassManageAction { @Resource private ClassService service; @ResponseBody @RequestMapping("/getAll")
// Path: src/main/java/com/zeven/course/model/Clazz.java // @Entity // public class Clazz { // private int id; // private String name; // private int deptId; // // @Id // @Column(name = "id", nullable = false) // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // @Basic // @Column(name = "name", nullable = false, length = 45) // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Basic // @Column(name = "dept_id", nullable = false) // public int getDeptId() { // return deptId; // } // // public void setDeptId(int deptId) { // this.deptId = deptId; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Clazz clazz = (Clazz) o; // // if (id != clazz.id) return false; // if (deptId != clazz.deptId) return false; // if (name != null ? !name.equals(clazz.name) : clazz.name != null) return false; // // return true; // } // // @Override // public int hashCode() { // int result = id; // result = 31 * result + (name != null ? name.hashCode() : 0); // result = 31 * result + deptId; // return result; // } // } // // Path: src/main/java/com/zeven/course/service/ClassService.java // @Component // public class ClassService extends DaoSupportImpl<Clazz> { // // } // // Path: src/main/java/com/zeven/course/util/Message.java // public class Message { // private int code; // private String msg; // private Object data = ""; // // public Message() { // } // // public Message(int code, String msg) { // this.code = code; // this.msg = msg; // } // // public Message(int code, String msg, Object data) { // this.code = code; // this.msg = msg; // this.data = data; // } // // public int getCode() { // return code; // } // // public void setCode(int code) { // this.code = code; // } // // public String getMsg() { // return msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // // public Object getData() { // return data; // } // // public void setData(Object data) { // this.data = data; // } // } // Path: src/main/java/com/zeven/course/action/ClassManageAction.java import com.zeven.course.model.Clazz; import com.zeven.course.service.ClassService; import com.zeven.course.util.Message; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import javax.annotation.Resource; package com.zeven.course.action; /** * Created by fangf on 2016/5/20. */ @RequestMapping("/Admin/class") @Controller public class ClassManageAction { @Resource private ClassService service; @ResponseBody @RequestMapping("/getAll")
public Message getAll(){
ZevenFang/zevencourse
src/main/java/com/zeven/course/action/ClassManageAction.java
// Path: src/main/java/com/zeven/course/model/Clazz.java // @Entity // public class Clazz { // private int id; // private String name; // private int deptId; // // @Id // @Column(name = "id", nullable = false) // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // @Basic // @Column(name = "name", nullable = false, length = 45) // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Basic // @Column(name = "dept_id", nullable = false) // public int getDeptId() { // return deptId; // } // // public void setDeptId(int deptId) { // this.deptId = deptId; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Clazz clazz = (Clazz) o; // // if (id != clazz.id) return false; // if (deptId != clazz.deptId) return false; // if (name != null ? !name.equals(clazz.name) : clazz.name != null) return false; // // return true; // } // // @Override // public int hashCode() { // int result = id; // result = 31 * result + (name != null ? name.hashCode() : 0); // result = 31 * result + deptId; // return result; // } // } // // Path: src/main/java/com/zeven/course/service/ClassService.java // @Component // public class ClassService extends DaoSupportImpl<Clazz> { // // } // // Path: src/main/java/com/zeven/course/util/Message.java // public class Message { // private int code; // private String msg; // private Object data = ""; // // public Message() { // } // // public Message(int code, String msg) { // this.code = code; // this.msg = msg; // } // // public Message(int code, String msg, Object data) { // this.code = code; // this.msg = msg; // this.data = data; // } // // public int getCode() { // return code; // } // // public void setCode(int code) { // this.code = code; // } // // public String getMsg() { // return msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // // public Object getData() { // return data; // } // // public void setData(Object data) { // this.data = data; // } // }
import com.zeven.course.model.Clazz; import com.zeven.course.service.ClassService; import com.zeven.course.util.Message; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import javax.annotation.Resource;
package com.zeven.course.action; /** * Created by fangf on 2016/5/20. */ @RequestMapping("/Admin/class") @Controller public class ClassManageAction { @Resource private ClassService service; @ResponseBody @RequestMapping("/getAll") public Message getAll(){ return new Message(1,"ok",service.findAll()); } @ResponseBody @RequestMapping("/add") public Message add(@RequestParam String name, @RequestParam int deptId){ if (service.isFieldExisted("name",name)) return new Message(-1,"已存在“"+name+"”");
// Path: src/main/java/com/zeven/course/model/Clazz.java // @Entity // public class Clazz { // private int id; // private String name; // private int deptId; // // @Id // @Column(name = "id", nullable = false) // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // @Basic // @Column(name = "name", nullable = false, length = 45) // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Basic // @Column(name = "dept_id", nullable = false) // public int getDeptId() { // return deptId; // } // // public void setDeptId(int deptId) { // this.deptId = deptId; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Clazz clazz = (Clazz) o; // // if (id != clazz.id) return false; // if (deptId != clazz.deptId) return false; // if (name != null ? !name.equals(clazz.name) : clazz.name != null) return false; // // return true; // } // // @Override // public int hashCode() { // int result = id; // result = 31 * result + (name != null ? name.hashCode() : 0); // result = 31 * result + deptId; // return result; // } // } // // Path: src/main/java/com/zeven/course/service/ClassService.java // @Component // public class ClassService extends DaoSupportImpl<Clazz> { // // } // // Path: src/main/java/com/zeven/course/util/Message.java // public class Message { // private int code; // private String msg; // private Object data = ""; // // public Message() { // } // // public Message(int code, String msg) { // this.code = code; // this.msg = msg; // } // // public Message(int code, String msg, Object data) { // this.code = code; // this.msg = msg; // this.data = data; // } // // public int getCode() { // return code; // } // // public void setCode(int code) { // this.code = code; // } // // public String getMsg() { // return msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // // public Object getData() { // return data; // } // // public void setData(Object data) { // this.data = data; // } // } // Path: src/main/java/com/zeven/course/action/ClassManageAction.java import com.zeven.course.model.Clazz; import com.zeven.course.service.ClassService; import com.zeven.course.util.Message; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import javax.annotation.Resource; package com.zeven.course.action; /** * Created by fangf on 2016/5/20. */ @RequestMapping("/Admin/class") @Controller public class ClassManageAction { @Resource private ClassService service; @ResponseBody @RequestMapping("/getAll") public Message getAll(){ return new Message(1,"ok",service.findAll()); } @ResponseBody @RequestMapping("/add") public Message add(@RequestParam String name, @RequestParam int deptId){ if (service.isFieldExisted("name",name)) return new Message(-1,"已存在“"+name+"”");
Clazz clazz = new Clazz();
FAOSTAT/faostat-api
faostat-api-web/src/main/java/org/fao/faostat/api/web/utils/FAOSTATAPIUtils.java
// Path: faostat-api-core/src/main/java/org/fao/faostat/api/core/beans/MetadataBean.java // public class MetadataBean { // // private DATASOURCE datasource; // // private String apiKey; // // private String clientKey; // // private OUTPUTTYPE outputType; // // private List<String> blackList; // // private List<String> whiteList; // // private Map<String, Object> procedureParameters; // // private List<Map<String, Object>> dsd; // // private Boolean pivot = false; // // private Boolean full = false; // // private Long processingTime; // // public MetadataBean() { // this.setDatasource(DATASOURCE.PRODUCTION); // this.setApiKey(null); // this.setClientKey(null); // this.setOutputType(OUTPUTTYPE.OBJECTS); // this.setProcedureParameters(new HashMap<String, Object>()); // this.setDsd(new ArrayList<Map<String, Object>>()); // this.setClientKey(null); // } // // public MetadataBean(String datasource, String apiKey, String clientKey, String outputType) { // this.storeUserOptions(datasource, apiKey, clientKey, outputType); // } // // public void storeUserOptions(String datasource, String apiKey, String clientKey, String outputType) { // this.setDatasource(datasource != null ? DATASOURCE.valueOf(datasource.toUpperCase()) : DATASOURCE.PRODUCTION); // this.setApiKey(apiKey != null ? apiKey : this.getApiKey()); // this.setClientKey(clientKey != null ? clientKey : this.getClientKey()); // this.setOutputType(outputType != null ? OUTPUTTYPE.valueOf(outputType.toUpperCase()) : OUTPUTTYPE.OBJECTS); // this.setProcedureParameters(new HashMap<String, Object>()); // this.setDsd(new ArrayList<Map<String, Object>>()); // } // // public List<String> getBlackList() { // return blackList; // } // // public void setBlackList(List<String> blackList) { // this.blackList = blackList; // } // // public List<String> getWhiteList() { // return whiteList; // } // // public void setWhiteList(List<String> whiteList) { // this.whiteList = whiteList; // } // // public void addParameter(String key, Object value) { // this.getProcedureParameters().put(key, value); // } // // public void addParameters(Map<String, Object> params) { // this.getProcedureParameters().putAll(params); // } // // public DATASOURCE getDatasource() { // return datasource; // } // // public void setDatasource(DATASOURCE datasource) { // this.datasource = datasource; // } // // public String getApiKey() { // return apiKey; // } // // public void setApiKey(String apiKey) { // this.apiKey = apiKey; // } // // public String getClientKey() { // return clientKey; // } // // public void setClientKey(String clientKey) { // this.clientKey = clientKey; // } // // public OUTPUTTYPE getOutputType() { // return outputType; // } // // public void setOutputType(OUTPUTTYPE outputType) { // this.outputType = outputType; // } // // public Map<String, Object> getProcedureParameters() { // return procedureParameters; // } // // public void setProcedureParameters(Map<String, Object> procedureParameters) { // this.procedureParameters = procedureParameters; // } // // public Boolean getPivot() { // return pivot; // } // // public void setPivot(Boolean pivot) { // this.pivot = pivot; // } // // public List<Map<String, Object>> getDsd() { // return dsd; // } // // public void setDsd(List<Map<String, Object>> dsd) { // this.dsd = dsd; // } // // public Long getProcessingTime() { // return processingTime; // } // // public void setProcessingTime(Long processingTime) { // this.processingTime = processingTime; // } // // public Boolean getFull() { return full; } // // public void setFull(Boolean full) { // if (full != null ) { // this.full = full; // } // } // // @Override // public String toString() { // return "MetadataBean{" + // "datasource='" + datasource + '\'' + // ", apiKey='" + apiKey + '\'' + // ", clientKey='" + clientKey + '\'' + // ", outputType=" + outputType + // ", blackList=" + blackList + // ", whiteList=" + whiteList + // ", procedureParameters=" + procedureParameters + // ", pivot=" + pivot + // ", full=" + full + // ", dsd=" + dsd + // ", processingTime=" + processingTime + // '}'; // } // // } // // Path: faostat-api-core/src/main/java/org/fao/faostat/api/core/constants/OUTPUTTYPE.java // public enum OUTPUTTYPE { // // ARRAYS, CSV, JSON, OBJECTS; // // }
import org.fao.faostat.api.core.beans.MetadataBean; import org.fao.faostat.api.core.constants.OUTPUTTYPE; import javax.ws.rs.core.MediaType; import java.util.ArrayList; import java.util.List; import java.util.Map;
package org.fao.faostat.api.web.utils; public class FAOSTATAPIUtils { public static String outputType(MetadataBean metadataBean) {
// Path: faostat-api-core/src/main/java/org/fao/faostat/api/core/beans/MetadataBean.java // public class MetadataBean { // // private DATASOURCE datasource; // // private String apiKey; // // private String clientKey; // // private OUTPUTTYPE outputType; // // private List<String> blackList; // // private List<String> whiteList; // // private Map<String, Object> procedureParameters; // // private List<Map<String, Object>> dsd; // // private Boolean pivot = false; // // private Boolean full = false; // // private Long processingTime; // // public MetadataBean() { // this.setDatasource(DATASOURCE.PRODUCTION); // this.setApiKey(null); // this.setClientKey(null); // this.setOutputType(OUTPUTTYPE.OBJECTS); // this.setProcedureParameters(new HashMap<String, Object>()); // this.setDsd(new ArrayList<Map<String, Object>>()); // this.setClientKey(null); // } // // public MetadataBean(String datasource, String apiKey, String clientKey, String outputType) { // this.storeUserOptions(datasource, apiKey, clientKey, outputType); // } // // public void storeUserOptions(String datasource, String apiKey, String clientKey, String outputType) { // this.setDatasource(datasource != null ? DATASOURCE.valueOf(datasource.toUpperCase()) : DATASOURCE.PRODUCTION); // this.setApiKey(apiKey != null ? apiKey : this.getApiKey()); // this.setClientKey(clientKey != null ? clientKey : this.getClientKey()); // this.setOutputType(outputType != null ? OUTPUTTYPE.valueOf(outputType.toUpperCase()) : OUTPUTTYPE.OBJECTS); // this.setProcedureParameters(new HashMap<String, Object>()); // this.setDsd(new ArrayList<Map<String, Object>>()); // } // // public List<String> getBlackList() { // return blackList; // } // // public void setBlackList(List<String> blackList) { // this.blackList = blackList; // } // // public List<String> getWhiteList() { // return whiteList; // } // // public void setWhiteList(List<String> whiteList) { // this.whiteList = whiteList; // } // // public void addParameter(String key, Object value) { // this.getProcedureParameters().put(key, value); // } // // public void addParameters(Map<String, Object> params) { // this.getProcedureParameters().putAll(params); // } // // public DATASOURCE getDatasource() { // return datasource; // } // // public void setDatasource(DATASOURCE datasource) { // this.datasource = datasource; // } // // public String getApiKey() { // return apiKey; // } // // public void setApiKey(String apiKey) { // this.apiKey = apiKey; // } // // public String getClientKey() { // return clientKey; // } // // public void setClientKey(String clientKey) { // this.clientKey = clientKey; // } // // public OUTPUTTYPE getOutputType() { // return outputType; // } // // public void setOutputType(OUTPUTTYPE outputType) { // this.outputType = outputType; // } // // public Map<String, Object> getProcedureParameters() { // return procedureParameters; // } // // public void setProcedureParameters(Map<String, Object> procedureParameters) { // this.procedureParameters = procedureParameters; // } // // public Boolean getPivot() { // return pivot; // } // // public void setPivot(Boolean pivot) { // this.pivot = pivot; // } // // public List<Map<String, Object>> getDsd() { // return dsd; // } // // public void setDsd(List<Map<String, Object>> dsd) { // this.dsd = dsd; // } // // public Long getProcessingTime() { // return processingTime; // } // // public void setProcessingTime(Long processingTime) { // this.processingTime = processingTime; // } // // public Boolean getFull() { return full; } // // public void setFull(Boolean full) { // if (full != null ) { // this.full = full; // } // } // // @Override // public String toString() { // return "MetadataBean{" + // "datasource='" + datasource + '\'' + // ", apiKey='" + apiKey + '\'' + // ", clientKey='" + clientKey + '\'' + // ", outputType=" + outputType + // ", blackList=" + blackList + // ", whiteList=" + whiteList + // ", procedureParameters=" + procedureParameters + // ", pivot=" + pivot + // ", full=" + full + // ", dsd=" + dsd + // ", processingTime=" + processingTime + // '}'; // } // // } // // Path: faostat-api-core/src/main/java/org/fao/faostat/api/core/constants/OUTPUTTYPE.java // public enum OUTPUTTYPE { // // ARRAYS, CSV, JSON, OBJECTS; // // } // Path: faostat-api-web/src/main/java/org/fao/faostat/api/web/utils/FAOSTATAPIUtils.java import org.fao.faostat.api.core.beans.MetadataBean; import org.fao.faostat.api.core.constants.OUTPUTTYPE; import javax.ws.rs.core.MediaType; import java.util.ArrayList; import java.util.List; import java.util.Map; package org.fao.faostat.api.web.utils; public class FAOSTATAPIUtils { public static String outputType(MetadataBean metadataBean) {
if (metadataBean.getOutputType().equals(OUTPUTTYPE.CSV)) {
brarcher/rental-calc
app/src/test/java/protect/rentalcalc/PropertyViewActivityTest.java
// Path: app/src/test/java/protect/rentalcalc/TestHelper.java // static void checkIntField(int expected, String actual) // { // if(actual.isEmpty()) // { // assertEquals(expected, 0); // } // else // { // assertEquals(expected, Integer.parseInt(actual)); // } // } // // Path: app/src/test/java/protect/rentalcalc/TestHelper.java // static void preloadProperty(Property property) throws IllegalAccessException // { // // Set the fields to some non-default value which should be // // different for every field // for(Field field : property.getClass().getDeclaredFields()) // { // if(field.getType() == String.class) // { // String fieldName = field.getName(); // String value = fieldName; // // // These are spinners and the possible values are limited // if(fieldName.equals("propertyBeds")) // { // value = "5"; // } // else if(fieldName.equals("propertyBaths")) // { // value = "5.5"; // } // // field.set(property, value); // } // // if(field.getType() == Integer.TYPE) // { // String fieldName = field.getName(); // int value = Math.abs(fieldName.hashCode()); // // // These are spinners and the possible values are limited // if(fieldName.equals("propertyType")) // { // value = value % PropertyType.values().length; // } // else if(fieldName.equals("propertyParking")) // { // value = value % ParkingType.values().length; // } // // Map<String, Integer> maxLengths = new HashMap<>(); // maxLengths.put("purchasePrice", 13); // maxLengths.put("afterRepairsValue", 13); // maxLengths.put("downPayment", 3); // maxLengths.put("interestRate", 3); // maxLengths.put("loanDuration", 2); // maxLengths.put("purchaseCosts", 3); // maxLengths.put("repairRemodelCosts", 13); // maxLengths.put("grossRent", 7); // maxLengths.put("otherIncome", 7); // maxLengths.put("expenses", 6); // maxLengths.put("vacancy", 3); // maxLengths.put("appreciation", 3); // maxLengths.put("incomeIncrease", 3); // maxLengths.put("expenseIncrease", 3); // maxLengths.put("sellingCosts", 3); // maxLengths.put("landValue", 13); // maxLengths.put("incomeTaxRate", 3); // // if(maxLengths.containsKey(fieldName)) // { // String strValue = Integer.toString(value); // int maxLength = maxLengths.get(fieldName); // strValue = strValue.substring(0, Math.min(strValue.length(), maxLength)); // value = Integer.parseInt(strValue); // } // // field.set(property, value); // } // } // }
import android.app.Activity; import android.content.ComponentName; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.EditText; import android.widget.Spinner; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import org.robolectric.RobolectricTestRunner; import org.robolectric.RuntimeEnvironment; import org.robolectric.android.controller.ActivityController; import org.robolectric.annotation.Config; import org.robolectric.shadows.ShadowLog; import org.robolectric.shadows.ShadowToast; import java.util.Locale; import static org.junit.Assert.assertNotNull; import static protect.rentalcalc.TestHelper.checkIntField; import static protect.rentalcalc.TestHelper.preloadProperty; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.robolectric.Shadows.shadowOf;
assertEquals(menu.size(), 1); MenuItem item = menu.findItem(R.id.action_save); assertNotNull(item); assertEquals("Save", item.getTitle().toString()); } private void checkFields(Activity activity, Property property) { EditText nicknameField = (EditText)activity.findViewById(R.id.nickname); EditText streetField = (EditText)activity.findViewById(R.id.street); EditText cityField = (EditText)activity.findViewById(R.id.city); EditText stateField = (EditText)activity.findViewById(R.id.state); EditText zipField = (EditText)activity.findViewById(R.id.zip); Spinner typeSpinner = (Spinner)activity.findViewById(R.id.type); Spinner bedsSpinner = (Spinner)activity.findViewById(R.id.beds); Spinner bathsSpinner = (Spinner)activity.findViewById(R.id.baths); EditText sqftField = (EditText)activity.findViewById(R.id.sqft); EditText lotField = (EditText)activity.findViewById(R.id.lot); EditText yearField = (EditText)activity.findViewById(R.id.year); Spinner parkingSpinner = (Spinner)activity.findViewById(R.id.parking); EditText zoningField = (EditText)activity.findViewById(R.id.zoning); EditText mlsField = (EditText)activity.findViewById(R.id.mls); assertEquals(property.nickname, nicknameField.getText().toString()); assertEquals(property.addressStreet, streetField.getText().toString()); assertEquals(property.addressCity, cityField.getText().toString()); assertEquals(property.addressState, stateField.getText().toString()); assertEquals(property.addressZip, zipField.getText().toString());
// Path: app/src/test/java/protect/rentalcalc/TestHelper.java // static void checkIntField(int expected, String actual) // { // if(actual.isEmpty()) // { // assertEquals(expected, 0); // } // else // { // assertEquals(expected, Integer.parseInt(actual)); // } // } // // Path: app/src/test/java/protect/rentalcalc/TestHelper.java // static void preloadProperty(Property property) throws IllegalAccessException // { // // Set the fields to some non-default value which should be // // different for every field // for(Field field : property.getClass().getDeclaredFields()) // { // if(field.getType() == String.class) // { // String fieldName = field.getName(); // String value = fieldName; // // // These are spinners and the possible values are limited // if(fieldName.equals("propertyBeds")) // { // value = "5"; // } // else if(fieldName.equals("propertyBaths")) // { // value = "5.5"; // } // // field.set(property, value); // } // // if(field.getType() == Integer.TYPE) // { // String fieldName = field.getName(); // int value = Math.abs(fieldName.hashCode()); // // // These are spinners and the possible values are limited // if(fieldName.equals("propertyType")) // { // value = value % PropertyType.values().length; // } // else if(fieldName.equals("propertyParking")) // { // value = value % ParkingType.values().length; // } // // Map<String, Integer> maxLengths = new HashMap<>(); // maxLengths.put("purchasePrice", 13); // maxLengths.put("afterRepairsValue", 13); // maxLengths.put("downPayment", 3); // maxLengths.put("interestRate", 3); // maxLengths.put("loanDuration", 2); // maxLengths.put("purchaseCosts", 3); // maxLengths.put("repairRemodelCosts", 13); // maxLengths.put("grossRent", 7); // maxLengths.put("otherIncome", 7); // maxLengths.put("expenses", 6); // maxLengths.put("vacancy", 3); // maxLengths.put("appreciation", 3); // maxLengths.put("incomeIncrease", 3); // maxLengths.put("expenseIncrease", 3); // maxLengths.put("sellingCosts", 3); // maxLengths.put("landValue", 13); // maxLengths.put("incomeTaxRate", 3); // // if(maxLengths.containsKey(fieldName)) // { // String strValue = Integer.toString(value); // int maxLength = maxLengths.get(fieldName); // strValue = strValue.substring(0, Math.min(strValue.length(), maxLength)); // value = Integer.parseInt(strValue); // } // // field.set(property, value); // } // } // } // Path: app/src/test/java/protect/rentalcalc/PropertyViewActivityTest.java import android.app.Activity; import android.content.ComponentName; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.EditText; import android.widget.Spinner; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import org.robolectric.RobolectricTestRunner; import org.robolectric.RuntimeEnvironment; import org.robolectric.android.controller.ActivityController; import org.robolectric.annotation.Config; import org.robolectric.shadows.ShadowLog; import org.robolectric.shadows.ShadowToast; import java.util.Locale; import static org.junit.Assert.assertNotNull; import static protect.rentalcalc.TestHelper.checkIntField; import static protect.rentalcalc.TestHelper.preloadProperty; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.robolectric.Shadows.shadowOf; assertEquals(menu.size(), 1); MenuItem item = menu.findItem(R.id.action_save); assertNotNull(item); assertEquals("Save", item.getTitle().toString()); } private void checkFields(Activity activity, Property property) { EditText nicknameField = (EditText)activity.findViewById(R.id.nickname); EditText streetField = (EditText)activity.findViewById(R.id.street); EditText cityField = (EditText)activity.findViewById(R.id.city); EditText stateField = (EditText)activity.findViewById(R.id.state); EditText zipField = (EditText)activity.findViewById(R.id.zip); Spinner typeSpinner = (Spinner)activity.findViewById(R.id.type); Spinner bedsSpinner = (Spinner)activity.findViewById(R.id.beds); Spinner bathsSpinner = (Spinner)activity.findViewById(R.id.baths); EditText sqftField = (EditText)activity.findViewById(R.id.sqft); EditText lotField = (EditText)activity.findViewById(R.id.lot); EditText yearField = (EditText)activity.findViewById(R.id.year); Spinner parkingSpinner = (Spinner)activity.findViewById(R.id.parking); EditText zoningField = (EditText)activity.findViewById(R.id.zoning); EditText mlsField = (EditText)activity.findViewById(R.id.mls); assertEquals(property.nickname, nicknameField.getText().toString()); assertEquals(property.addressStreet, streetField.getText().toString()); assertEquals(property.addressCity, cityField.getText().toString()); assertEquals(property.addressState, stateField.getText().toString()); assertEquals(property.addressZip, zipField.getText().toString());
checkIntField(property.propertySqft, sqftField.getText().toString());
brarcher/rental-calc
app/src/test/java/protect/rentalcalc/PropertyViewActivityTest.java
// Path: app/src/test/java/protect/rentalcalc/TestHelper.java // static void checkIntField(int expected, String actual) // { // if(actual.isEmpty()) // { // assertEquals(expected, 0); // } // else // { // assertEquals(expected, Integer.parseInt(actual)); // } // } // // Path: app/src/test/java/protect/rentalcalc/TestHelper.java // static void preloadProperty(Property property) throws IllegalAccessException // { // // Set the fields to some non-default value which should be // // different for every field // for(Field field : property.getClass().getDeclaredFields()) // { // if(field.getType() == String.class) // { // String fieldName = field.getName(); // String value = fieldName; // // // These are spinners and the possible values are limited // if(fieldName.equals("propertyBeds")) // { // value = "5"; // } // else if(fieldName.equals("propertyBaths")) // { // value = "5.5"; // } // // field.set(property, value); // } // // if(field.getType() == Integer.TYPE) // { // String fieldName = field.getName(); // int value = Math.abs(fieldName.hashCode()); // // // These are spinners and the possible values are limited // if(fieldName.equals("propertyType")) // { // value = value % PropertyType.values().length; // } // else if(fieldName.equals("propertyParking")) // { // value = value % ParkingType.values().length; // } // // Map<String, Integer> maxLengths = new HashMap<>(); // maxLengths.put("purchasePrice", 13); // maxLengths.put("afterRepairsValue", 13); // maxLengths.put("downPayment", 3); // maxLengths.put("interestRate", 3); // maxLengths.put("loanDuration", 2); // maxLengths.put("purchaseCosts", 3); // maxLengths.put("repairRemodelCosts", 13); // maxLengths.put("grossRent", 7); // maxLengths.put("otherIncome", 7); // maxLengths.put("expenses", 6); // maxLengths.put("vacancy", 3); // maxLengths.put("appreciation", 3); // maxLengths.put("incomeIncrease", 3); // maxLengths.put("expenseIncrease", 3); // maxLengths.put("sellingCosts", 3); // maxLengths.put("landValue", 13); // maxLengths.put("incomeTaxRate", 3); // // if(maxLengths.containsKey(fieldName)) // { // String strValue = Integer.toString(value); // int maxLength = maxLengths.get(fieldName); // strValue = strValue.substring(0, Math.min(strValue.length(), maxLength)); // value = Integer.parseInt(strValue); // } // // field.set(property, value); // } // } // }
import android.app.Activity; import android.content.ComponentName; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.EditText; import android.widget.Spinner; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import org.robolectric.RobolectricTestRunner; import org.robolectric.RuntimeEnvironment; import org.robolectric.android.controller.ActivityController; import org.robolectric.annotation.Config; import org.robolectric.shadows.ShadowLog; import org.robolectric.shadows.ShadowToast; import java.util.Locale; import static org.junit.Assert.assertNotNull; import static protect.rentalcalc.TestHelper.checkIntField; import static protect.rentalcalc.TestHelper.preloadProperty; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.robolectric.Shadows.shadowOf;
checkFields(activity, new Property()); } @Test public void startWithoutProperty() { Intent intent = new Intent(); final Bundle bundle = new Bundle(); intent.putExtras(bundle); ActivityController controller = Robolectric.buildActivity(PropertyViewActivity.class, intent).create(); Activity activity = (Activity)controller.get(); checkFields(activity, new Property()); } @Test public void startWithoutPropertyAndSave() throws IllegalAccessException { Intent intent = new Intent(); final Bundle bundle = new Bundle(); intent.putExtras(bundle); ActivityController controller = Robolectric.buildActivity(PropertyViewActivity.class, intent).create(); Activity activity = (Activity)controller.get(); controller.start(); controller.visible(); controller.resume(); Property property = new Property();
// Path: app/src/test/java/protect/rentalcalc/TestHelper.java // static void checkIntField(int expected, String actual) // { // if(actual.isEmpty()) // { // assertEquals(expected, 0); // } // else // { // assertEquals(expected, Integer.parseInt(actual)); // } // } // // Path: app/src/test/java/protect/rentalcalc/TestHelper.java // static void preloadProperty(Property property) throws IllegalAccessException // { // // Set the fields to some non-default value which should be // // different for every field // for(Field field : property.getClass().getDeclaredFields()) // { // if(field.getType() == String.class) // { // String fieldName = field.getName(); // String value = fieldName; // // // These are spinners and the possible values are limited // if(fieldName.equals("propertyBeds")) // { // value = "5"; // } // else if(fieldName.equals("propertyBaths")) // { // value = "5.5"; // } // // field.set(property, value); // } // // if(field.getType() == Integer.TYPE) // { // String fieldName = field.getName(); // int value = Math.abs(fieldName.hashCode()); // // // These are spinners and the possible values are limited // if(fieldName.equals("propertyType")) // { // value = value % PropertyType.values().length; // } // else if(fieldName.equals("propertyParking")) // { // value = value % ParkingType.values().length; // } // // Map<String, Integer> maxLengths = new HashMap<>(); // maxLengths.put("purchasePrice", 13); // maxLengths.put("afterRepairsValue", 13); // maxLengths.put("downPayment", 3); // maxLengths.put("interestRate", 3); // maxLengths.put("loanDuration", 2); // maxLengths.put("purchaseCosts", 3); // maxLengths.put("repairRemodelCosts", 13); // maxLengths.put("grossRent", 7); // maxLengths.put("otherIncome", 7); // maxLengths.put("expenses", 6); // maxLengths.put("vacancy", 3); // maxLengths.put("appreciation", 3); // maxLengths.put("incomeIncrease", 3); // maxLengths.put("expenseIncrease", 3); // maxLengths.put("sellingCosts", 3); // maxLengths.put("landValue", 13); // maxLengths.put("incomeTaxRate", 3); // // if(maxLengths.containsKey(fieldName)) // { // String strValue = Integer.toString(value); // int maxLength = maxLengths.get(fieldName); // strValue = strValue.substring(0, Math.min(strValue.length(), maxLength)); // value = Integer.parseInt(strValue); // } // // field.set(property, value); // } // } // } // Path: app/src/test/java/protect/rentalcalc/PropertyViewActivityTest.java import android.app.Activity; import android.content.ComponentName; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.EditText; import android.widget.Spinner; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import org.robolectric.RobolectricTestRunner; import org.robolectric.RuntimeEnvironment; import org.robolectric.android.controller.ActivityController; import org.robolectric.annotation.Config; import org.robolectric.shadows.ShadowLog; import org.robolectric.shadows.ShadowToast; import java.util.Locale; import static org.junit.Assert.assertNotNull; import static protect.rentalcalc.TestHelper.checkIntField; import static protect.rentalcalc.TestHelper.preloadProperty; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.robolectric.Shadows.shadowOf; checkFields(activity, new Property()); } @Test public void startWithoutProperty() { Intent intent = new Intent(); final Bundle bundle = new Bundle(); intent.putExtras(bundle); ActivityController controller = Robolectric.buildActivity(PropertyViewActivity.class, intent).create(); Activity activity = (Activity)controller.get(); checkFields(activity, new Property()); } @Test public void startWithoutPropertyAndSave() throws IllegalAccessException { Intent intent = new Intent(); final Bundle bundle = new Bundle(); intent.putExtras(bundle); ActivityController controller = Robolectric.buildActivity(PropertyViewActivity.class, intent).create(); Activity activity = (Activity)controller.get(); controller.start(); controller.visible(); controller.resume(); Property property = new Property();
preloadProperty(property);
zhihan/janala2-gradle
src/main/java/janala/logger/ObjectInfo.java
// Path: src/main/java/janala/interpreters/ClassDepot.java // public class ClassDepot implements Serializable { // private static final long serialVersionUID = 1; // // private final Map<String, ClassTemplate> templates; // // public static ClassDepot instance = new ClassDepot(); // // public static void setInstance(ClassDepot newInstance) { // instance = newInstance; // } // // public static ClassDepot getInstance() { // return instance; // } // // private static final Logger logger = MyLogger.getLogger(ClassDepot.class.getName()); // // // VisibleForTesting // public ClassDepot() { // templates = new TreeMap<String, ClassTemplate>(); // } // // private ClassTemplate getOrCreateTemplate(String className, Class<?> clazz) { // ClassTemplate ct = templates.get(className); // if (ct != null) { // return ct; // } // ct = new ClassTemplate(clazz); // templates.put(className, ct); // Class<?> parent = clazz.getSuperclass(); // if (parent != null) { // ClassTemplate pt = getOrCreateTemplate(parent.getName(), parent); // ct.addFields(pt); // } // return ct; // } // // public int getFieldIndex(String className, String field) { // try { // Class<?> clazz = Class.forName(className); // ClassTemplate ct = getOrCreateTemplate(className, clazz); // return ct.getFieldIndex(field); // } catch (ClassNotFoundException e) { // logger.log(Level.SEVERE, "", e); // return -1; // } // } // // public int getStaticFieldIndex(String className, String field) { // try { // Class<?> clazz = Class.forName(className); // ClassTemplate ct = getOrCreateTemplate(className, clazz); // return ct.getStaticFieldIndex(field); // } catch (ClassNotFoundException e) { // logger.log(Level.SEVERE, "", e); // return -1; // } // } // // public int numFields(String className) { // try { // Class<?> clazz = Class.forName(className); // ClassTemplate ct = getOrCreateTemplate(className, clazz); // return ct.nFields(); // } catch (ClassNotFoundException e) { // logger.log(Level.SEVERE, "Class not found", e); // return -1; // } // } // // public int numStaticFields(String className) { // try { // Class<?> clazz = Class.forName(className); // ClassTemplate ct = getOrCreateTemplate(className, clazz); // return ct.nStaticFields(); // } catch (ClassNotFoundException e) { // logger.log(Level.SEVERE, "", e); // return -1; // } // } // }
import janala.interpreters.ClassDepot; import janala.interpreters.PlaceHolder; import janala.interpreters.Value; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.Arrays; import java.util.Map; import java.util.TreeMap;
package janala.logger; /** * Containing the static info of a class and dynamic values of the * static fields. */ public class ObjectInfo implements Serializable { private static final long serialVersionUID = 1L; private Map<String, Integer> fieldNameToIndex; private List<FieldInfo> fieldList; private Map<String, Integer> staticFieldNameToIndex; private List<FieldInfo> staticFieldList; int nStaticFields; private int nFields; public Value[] statics; private String className; public String getClassName() { return className; }
// Path: src/main/java/janala/interpreters/ClassDepot.java // public class ClassDepot implements Serializable { // private static final long serialVersionUID = 1; // // private final Map<String, ClassTemplate> templates; // // public static ClassDepot instance = new ClassDepot(); // // public static void setInstance(ClassDepot newInstance) { // instance = newInstance; // } // // public static ClassDepot getInstance() { // return instance; // } // // private static final Logger logger = MyLogger.getLogger(ClassDepot.class.getName()); // // // VisibleForTesting // public ClassDepot() { // templates = new TreeMap<String, ClassTemplate>(); // } // // private ClassTemplate getOrCreateTemplate(String className, Class<?> clazz) { // ClassTemplate ct = templates.get(className); // if (ct != null) { // return ct; // } // ct = new ClassTemplate(clazz); // templates.put(className, ct); // Class<?> parent = clazz.getSuperclass(); // if (parent != null) { // ClassTemplate pt = getOrCreateTemplate(parent.getName(), parent); // ct.addFields(pt); // } // return ct; // } // // public int getFieldIndex(String className, String field) { // try { // Class<?> clazz = Class.forName(className); // ClassTemplate ct = getOrCreateTemplate(className, clazz); // return ct.getFieldIndex(field); // } catch (ClassNotFoundException e) { // logger.log(Level.SEVERE, "", e); // return -1; // } // } // // public int getStaticFieldIndex(String className, String field) { // try { // Class<?> clazz = Class.forName(className); // ClassTemplate ct = getOrCreateTemplate(className, clazz); // return ct.getStaticFieldIndex(field); // } catch (ClassNotFoundException e) { // logger.log(Level.SEVERE, "", e); // return -1; // } // } // // public int numFields(String className) { // try { // Class<?> clazz = Class.forName(className); // ClassTemplate ct = getOrCreateTemplate(className, clazz); // return ct.nFields(); // } catch (ClassNotFoundException e) { // logger.log(Level.SEVERE, "Class not found", e); // return -1; // } // } // // public int numStaticFields(String className) { // try { // Class<?> clazz = Class.forName(className); // ClassTemplate ct = getOrCreateTemplate(className, clazz); // return ct.nStaticFields(); // } catch (ClassNotFoundException e) { // logger.log(Level.SEVERE, "", e); // return -1; // } // } // } // Path: src/main/java/janala/logger/ObjectInfo.java import janala.interpreters.ClassDepot; import janala.interpreters.PlaceHolder; import janala.interpreters.Value; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.Arrays; import java.util.Map; import java.util.TreeMap; package janala.logger; /** * Containing the static info of a class and dynamic values of the * static fields. */ public class ObjectInfo implements Serializable { private static final long serialVersionUID = 1L; private Map<String, Integer> fieldNameToIndex; private List<FieldInfo> fieldList; private Map<String, Integer> staticFieldNameToIndex; private List<FieldInfo> staticFieldList; int nStaticFields; private int nFields; public Value[] statics; private String className; public String getClassName() { return className; }
private final ClassDepot classDepot;
zhihan/janala2-gradle
src/integration/java/tests/Testme.java
// Path: src/main/java/catg/CATG.java // public class CATG { // /** */ // public static int abstractInt(int value) { // int inputValue = readInt(value); // Main.abstractEqualsConcrete(Main.compare(inputValue, value)); // return inputValue; // } // // public static boolean abstractBool(String test, boolean x) { // boolean y = readBool(x); // Main.abstractEqualsConcrete(Main.compare(y, x)); // return y; // } // // public static long abstractLong(String test, long x) { // long y = readLong(x); // Main.abstractEqualsConcrete(Main.compare(y, x)); // return y; // } // // public static char abstractChar(String test, char x) { // char y = readChar(x); // Main.abstractEqualsConcrete(Main.compare(y, x)); // return y; // } // // public static byte abstractByte(String test, byte x) { // byte y = readByte(x); // Main.abstractEqualsConcrete(Main.compare(y, x)); // return y; // } // // public static short abstractShort(String test, short x) { // short y = readShort(x); // Main.abstractEqualsConcrete(Main.compare(y, x)); // return y; // } // // public static String abstractString(String test, String x) { // String y = readString(x); // Main.abstractEqualsConcrete(Main.compare(y, x)); // return y; // } // // public static int[] readIntArray(int length, int x) { // int[] ret = new int[length]; // for (int i = 0; i < length; i++) { // ret[i] = readInt(x); // } // return ret; // } // // public static int readInt(int x) { // int y = Main.readInt(x); // Main.MakeSymbolic(y); // Main.assume(y <= Integer.MAX_VALUE ? 1 : 0); // Main.assume(y >= Integer.MIN_VALUE ? 1 : 0); // return y; // } // // public static long readLong(long x) { // long y = Main.readLong(x); // Main.MakeSymbolic(y); // Main.assume(y <= Long.MAX_VALUE ? 1 : 0); // Main.assume(y >= Long.MIN_VALUE + 1 ? 1 : 0); // return y; // } // // public static char readChar(char x) { // char y = Main.readChar(x); // Main.MakeSymbolic(y); // Main.assume(y <= Character.MAX_VALUE ? 1 : 0); // Main.assume(y >= Character.MIN_VALUE ? 1 : 0); // return y; // } // // public static byte readByte(byte x) { // byte y = Main.readByte(x); // Main.MakeSymbolic(y); // Main.assume(y <= Byte.MAX_VALUE ? 1 : 0); // Main.assume(y >= Byte.MIN_VALUE ? 1 : 0); // return y; // } // // public static short readShort(short x) { // short y = Main.readShort(x); // Main.MakeSymbolic(y); // Main.assume(y <= Short.MAX_VALUE ? 1 : 0); // Main.assume(y >= Short.MIN_VALUE ? 1 : 0); // return y; // } // // public static boolean readBool(boolean x) { // boolean y = Main.readBool(x); // Main.MakeSymbolic(y); // OrValue tmp; // Main.ignore(); // tmp = Main.assumeOrBegin(y == true ? 1 : 0); // Main.ignore(); // tmp = Main.assumeOr(!y ? 1 : 0, tmp); // if (tmp != null) { // Main.assumeOrEnd(tmp); // } // return y; // } // // public static String readString(String x) { // String y = Main.readString(x); // Main.MakeSymbolic(y); // return y; // } // // public static boolean assertIfPossible(int pathId, boolean predicate) { // if (pathId == Config.instance.pathId) { // Main.forceTruth(predicate ? 1 : 0); // } // return predicate; // } // // public static void BeginScope() { // Main.beginScope(); // } // // public static void EndScope() { // Main.endScope(); // } // // public static void event(String eventName) { // Main.event(eventName); // } // // public static void pathRegex(String test, String regex) { // Main.pathRegex(regex); // } // // public static void equivalent(String test, String location, Serializable value) { // Main.equivalent(location, value); // } // // public static void skipPath() { // Main.skipPath(); // } // }
import catg.CATG;
package tests; public class Testme { private static int foo(int y) { return 2*y; } public static void testme(int x,int y){ int z = foo(y); if(z==x){ if(x>y+10){ System.err.println("Error"); // ERROR } } } public static void main(String[] args){
// Path: src/main/java/catg/CATG.java // public class CATG { // /** */ // public static int abstractInt(int value) { // int inputValue = readInt(value); // Main.abstractEqualsConcrete(Main.compare(inputValue, value)); // return inputValue; // } // // public static boolean abstractBool(String test, boolean x) { // boolean y = readBool(x); // Main.abstractEqualsConcrete(Main.compare(y, x)); // return y; // } // // public static long abstractLong(String test, long x) { // long y = readLong(x); // Main.abstractEqualsConcrete(Main.compare(y, x)); // return y; // } // // public static char abstractChar(String test, char x) { // char y = readChar(x); // Main.abstractEqualsConcrete(Main.compare(y, x)); // return y; // } // // public static byte abstractByte(String test, byte x) { // byte y = readByte(x); // Main.abstractEqualsConcrete(Main.compare(y, x)); // return y; // } // // public static short abstractShort(String test, short x) { // short y = readShort(x); // Main.abstractEqualsConcrete(Main.compare(y, x)); // return y; // } // // public static String abstractString(String test, String x) { // String y = readString(x); // Main.abstractEqualsConcrete(Main.compare(y, x)); // return y; // } // // public static int[] readIntArray(int length, int x) { // int[] ret = new int[length]; // for (int i = 0; i < length; i++) { // ret[i] = readInt(x); // } // return ret; // } // // public static int readInt(int x) { // int y = Main.readInt(x); // Main.MakeSymbolic(y); // Main.assume(y <= Integer.MAX_VALUE ? 1 : 0); // Main.assume(y >= Integer.MIN_VALUE ? 1 : 0); // return y; // } // // public static long readLong(long x) { // long y = Main.readLong(x); // Main.MakeSymbolic(y); // Main.assume(y <= Long.MAX_VALUE ? 1 : 0); // Main.assume(y >= Long.MIN_VALUE + 1 ? 1 : 0); // return y; // } // // public static char readChar(char x) { // char y = Main.readChar(x); // Main.MakeSymbolic(y); // Main.assume(y <= Character.MAX_VALUE ? 1 : 0); // Main.assume(y >= Character.MIN_VALUE ? 1 : 0); // return y; // } // // public static byte readByte(byte x) { // byte y = Main.readByte(x); // Main.MakeSymbolic(y); // Main.assume(y <= Byte.MAX_VALUE ? 1 : 0); // Main.assume(y >= Byte.MIN_VALUE ? 1 : 0); // return y; // } // // public static short readShort(short x) { // short y = Main.readShort(x); // Main.MakeSymbolic(y); // Main.assume(y <= Short.MAX_VALUE ? 1 : 0); // Main.assume(y >= Short.MIN_VALUE ? 1 : 0); // return y; // } // // public static boolean readBool(boolean x) { // boolean y = Main.readBool(x); // Main.MakeSymbolic(y); // OrValue tmp; // Main.ignore(); // tmp = Main.assumeOrBegin(y == true ? 1 : 0); // Main.ignore(); // tmp = Main.assumeOr(!y ? 1 : 0, tmp); // if (tmp != null) { // Main.assumeOrEnd(tmp); // } // return y; // } // // public static String readString(String x) { // String y = Main.readString(x); // Main.MakeSymbolic(y); // return y; // } // // public static boolean assertIfPossible(int pathId, boolean predicate) { // if (pathId == Config.instance.pathId) { // Main.forceTruth(predicate ? 1 : 0); // } // return predicate; // } // // public static void BeginScope() { // Main.beginScope(); // } // // public static void EndScope() { // Main.endScope(); // } // // public static void event(String eventName) { // Main.event(eventName); // } // // public static void pathRegex(String test, String regex) { // Main.pathRegex(regex); // } // // public static void equivalent(String test, String location, Serializable value) { // Main.equivalent(location, value); // } // // public static void skipPath() { // Main.skipPath(); // } // } // Path: src/integration/java/tests/Testme.java import catg.CATG; package tests; public class Testme { private static int foo(int y) { return 2*y; } public static void testme(int x,int y){ int z = foo(y); if(z==x){ if(x>y+10){ System.err.println("Error"); // ERROR } } } public static void main(String[] args){
int x = CATG.readInt(2);
zhihan/janala2-gradle
src/main/java/janala/logger/ClassNames.java
// Path: src/main/java/janala/interpreters/ClassDepot.java // public class ClassDepot implements Serializable { // private static final long serialVersionUID = 1; // // private final Map<String, ClassTemplate> templates; // // public static ClassDepot instance = new ClassDepot(); // // public static void setInstance(ClassDepot newInstance) { // instance = newInstance; // } // // public static ClassDepot getInstance() { // return instance; // } // // private static final Logger logger = MyLogger.getLogger(ClassDepot.class.getName()); // // // VisibleForTesting // public ClassDepot() { // templates = new TreeMap<String, ClassTemplate>(); // } // // private ClassTemplate getOrCreateTemplate(String className, Class<?> clazz) { // ClassTemplate ct = templates.get(className); // if (ct != null) { // return ct; // } // ct = new ClassTemplate(clazz); // templates.put(className, ct); // Class<?> parent = clazz.getSuperclass(); // if (parent != null) { // ClassTemplate pt = getOrCreateTemplate(parent.getName(), parent); // ct.addFields(pt); // } // return ct; // } // // public int getFieldIndex(String className, String field) { // try { // Class<?> clazz = Class.forName(className); // ClassTemplate ct = getOrCreateTemplate(className, clazz); // return ct.getFieldIndex(field); // } catch (ClassNotFoundException e) { // logger.log(Level.SEVERE, "", e); // return -1; // } // } // // public int getStaticFieldIndex(String className, String field) { // try { // Class<?> clazz = Class.forName(className); // ClassTemplate ct = getOrCreateTemplate(className, clazz); // return ct.getStaticFieldIndex(field); // } catch (ClassNotFoundException e) { // logger.log(Level.SEVERE, "", e); // return -1; // } // } // // public int numFields(String className) { // try { // Class<?> clazz = Class.forName(className); // ClassTemplate ct = getOrCreateTemplate(className, clazz); // return ct.nFields(); // } catch (ClassNotFoundException e) { // logger.log(Level.SEVERE, "Class not found", e); // return -1; // } // } // // public int numStaticFields(String className) { // try { // Class<?> clazz = Class.forName(className); // ClassTemplate ct = getOrCreateTemplate(className, clazz); // return ct.nStaticFields(); // } catch (ClassNotFoundException e) { // logger.log(Level.SEVERE, "", e); // return -1; // } // } // }
import janala.interpreters.ClassDepot; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.TreeMap;
package janala.logger; public class ClassNames implements Serializable { public static final long serialVersionUID = 1L; private Map<String, Integer> nameToIndex; private List<ObjectInfo> classList; private static ClassNames instance = new ClassNames(); public static ClassNames getInstance() { return instance; }
// Path: src/main/java/janala/interpreters/ClassDepot.java // public class ClassDepot implements Serializable { // private static final long serialVersionUID = 1; // // private final Map<String, ClassTemplate> templates; // // public static ClassDepot instance = new ClassDepot(); // // public static void setInstance(ClassDepot newInstance) { // instance = newInstance; // } // // public static ClassDepot getInstance() { // return instance; // } // // private static final Logger logger = MyLogger.getLogger(ClassDepot.class.getName()); // // // VisibleForTesting // public ClassDepot() { // templates = new TreeMap<String, ClassTemplate>(); // } // // private ClassTemplate getOrCreateTemplate(String className, Class<?> clazz) { // ClassTemplate ct = templates.get(className); // if (ct != null) { // return ct; // } // ct = new ClassTemplate(clazz); // templates.put(className, ct); // Class<?> parent = clazz.getSuperclass(); // if (parent != null) { // ClassTemplate pt = getOrCreateTemplate(parent.getName(), parent); // ct.addFields(pt); // } // return ct; // } // // public int getFieldIndex(String className, String field) { // try { // Class<?> clazz = Class.forName(className); // ClassTemplate ct = getOrCreateTemplate(className, clazz); // return ct.getFieldIndex(field); // } catch (ClassNotFoundException e) { // logger.log(Level.SEVERE, "", e); // return -1; // } // } // // public int getStaticFieldIndex(String className, String field) { // try { // Class<?> clazz = Class.forName(className); // ClassTemplate ct = getOrCreateTemplate(className, clazz); // return ct.getStaticFieldIndex(field); // } catch (ClassNotFoundException e) { // logger.log(Level.SEVERE, "", e); // return -1; // } // } // // public int numFields(String className) { // try { // Class<?> clazz = Class.forName(className); // ClassTemplate ct = getOrCreateTemplate(className, clazz); // return ct.nFields(); // } catch (ClassNotFoundException e) { // logger.log(Level.SEVERE, "Class not found", e); // return -1; // } // } // // public int numStaticFields(String className) { // try { // Class<?> clazz = Class.forName(className); // ClassTemplate ct = getOrCreateTemplate(className, clazz); // return ct.nStaticFields(); // } catch (ClassNotFoundException e) { // logger.log(Level.SEVERE, "", e); // return -1; // } // } // } // Path: src/main/java/janala/logger/ClassNames.java import janala.interpreters.ClassDepot; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.TreeMap; package janala.logger; public class ClassNames implements Serializable { public static final long serialVersionUID = 1L; private Map<String, Integer> nameToIndex; private List<ObjectInfo> classList; private static ClassNames instance = new ClassNames(); public static ClassNames getInstance() { return instance; }
private final ClassDepot classDepot;
zhihan/janala2-gradle
src/main/java/janala/logger/FieldInfo.java
// Path: src/main/java/janala/interpreters/ClassDepot.java // public class ClassDepot implements Serializable { // private static final long serialVersionUID = 1; // // private final Map<String, ClassTemplate> templates; // // public static ClassDepot instance = new ClassDepot(); // // public static void setInstance(ClassDepot newInstance) { // instance = newInstance; // } // // public static ClassDepot getInstance() { // return instance; // } // // private static final Logger logger = MyLogger.getLogger(ClassDepot.class.getName()); // // // VisibleForTesting // public ClassDepot() { // templates = new TreeMap<String, ClassTemplate>(); // } // // private ClassTemplate getOrCreateTemplate(String className, Class<?> clazz) { // ClassTemplate ct = templates.get(className); // if (ct != null) { // return ct; // } // ct = new ClassTemplate(clazz); // templates.put(className, ct); // Class<?> parent = clazz.getSuperclass(); // if (parent != null) { // ClassTemplate pt = getOrCreateTemplate(parent.getName(), parent); // ct.addFields(pt); // } // return ct; // } // // public int getFieldIndex(String className, String field) { // try { // Class<?> clazz = Class.forName(className); // ClassTemplate ct = getOrCreateTemplate(className, clazz); // return ct.getFieldIndex(field); // } catch (ClassNotFoundException e) { // logger.log(Level.SEVERE, "", e); // return -1; // } // } // // public int getStaticFieldIndex(String className, String field) { // try { // Class<?> clazz = Class.forName(className); // ClassTemplate ct = getOrCreateTemplate(className, clazz); // return ct.getStaticFieldIndex(field); // } catch (ClassNotFoundException e) { // logger.log(Level.SEVERE, "", e); // return -1; // } // } // // public int numFields(String className) { // try { // Class<?> clazz = Class.forName(className); // ClassTemplate ct = getOrCreateTemplate(className, clazz); // return ct.nFields(); // } catch (ClassNotFoundException e) { // logger.log(Level.SEVERE, "Class not found", e); // return -1; // } // } // // public int numStaticFields(String className) { // try { // Class<?> clazz = Class.forName(className); // ClassTemplate ct = getOrCreateTemplate(className, clazz); // return ct.nStaticFields(); // } catch (ClassNotFoundException e) { // logger.log(Level.SEVERE, "", e); // return -1; // } // } // }
import janala.interpreters.ClassDepot; import java.io.Serializable;
package janala.logger; public class FieldInfo implements Serializable { private static final long serialVersionUID = 1L; private final String className; private final String fieldName; private final boolean isStatic;
// Path: src/main/java/janala/interpreters/ClassDepot.java // public class ClassDepot implements Serializable { // private static final long serialVersionUID = 1; // // private final Map<String, ClassTemplate> templates; // // public static ClassDepot instance = new ClassDepot(); // // public static void setInstance(ClassDepot newInstance) { // instance = newInstance; // } // // public static ClassDepot getInstance() { // return instance; // } // // private static final Logger logger = MyLogger.getLogger(ClassDepot.class.getName()); // // // VisibleForTesting // public ClassDepot() { // templates = new TreeMap<String, ClassTemplate>(); // } // // private ClassTemplate getOrCreateTemplate(String className, Class<?> clazz) { // ClassTemplate ct = templates.get(className); // if (ct != null) { // return ct; // } // ct = new ClassTemplate(clazz); // templates.put(className, ct); // Class<?> parent = clazz.getSuperclass(); // if (parent != null) { // ClassTemplate pt = getOrCreateTemplate(parent.getName(), parent); // ct.addFields(pt); // } // return ct; // } // // public int getFieldIndex(String className, String field) { // try { // Class<?> clazz = Class.forName(className); // ClassTemplate ct = getOrCreateTemplate(className, clazz); // return ct.getFieldIndex(field); // } catch (ClassNotFoundException e) { // logger.log(Level.SEVERE, "", e); // return -1; // } // } // // public int getStaticFieldIndex(String className, String field) { // try { // Class<?> clazz = Class.forName(className); // ClassTemplate ct = getOrCreateTemplate(className, clazz); // return ct.getStaticFieldIndex(field); // } catch (ClassNotFoundException e) { // logger.log(Level.SEVERE, "", e); // return -1; // } // } // // public int numFields(String className) { // try { // Class<?> clazz = Class.forName(className); // ClassTemplate ct = getOrCreateTemplate(className, clazz); // return ct.nFields(); // } catch (ClassNotFoundException e) { // logger.log(Level.SEVERE, "Class not found", e); // return -1; // } // } // // public int numStaticFields(String className) { // try { // Class<?> clazz = Class.forName(className); // ClassTemplate ct = getOrCreateTemplate(className, clazz); // return ct.nStaticFields(); // } catch (ClassNotFoundException e) { // logger.log(Level.SEVERE, "", e); // return -1; // } // } // } // Path: src/main/java/janala/logger/FieldInfo.java import janala.interpreters.ClassDepot; import java.io.Serializable; package janala.logger; public class FieldInfo implements Serializable { private static final long serialVersionUID = 1L; private final String className; private final String fieldName; private final boolean isStatic;
private final ClassDepot classDepot;
thebrightspark/SparksHammers
src/main/java/brightspark/sparkshammers/util/LogHelper.java
// Path: src/main/java/brightspark/sparkshammers/Reference.java // public class Reference // { // public static final String MOD_ID = "sparkshammers"; // public static final String MOD_NAME = "Spark's Hammers"; // public static final String VERSION = "@VERSION@"; // public static final String DEPENDENCIES = // "after:enderio;" + // "after:botania;" + // "after:mobhunter;" + // "after:jei"; // // public static final String ITEM_TEXTURE_DIR = MOD_ID + ":"; // public static final String GUI_TEXTURE_DIR = "textures/gui/"; // public static final File CONFIG_DIR = new File(Loader.instance().getConfigDir(), MOD_ID); // // public static class JEI // { // public static final String HAMMER_CRAFTING_UID = MOD_ID + ":hammerCrafting"; // public static final String HAMMER_CRAFTING_TITLE_UNLOC = "jei.recipe.hammerCraftingTable"; // } // // public static class UUIDs // { // public static final UUID BRIGHT_SPARK = UUID.fromString("4adad317-d08b-412d-a75b-c2834386b088"); // public static final UUID _8BRICKDMG = UUID.fromString("647c557d-b494-45cf-9be9-f9774348d4c1"); // } // // public static class Items // { // public static final String HAMMER = "hammer"; // public static final String EXCAVATOR = "excavator"; // } // // public static class Mods // { // public static final String BOTANIA = "botania"; // public static final String EXTRA_UTILITIES = "extrautils2"; // public static final String ENDERIO = "enderio"; // } // // public static class ModItemIds // { // public static final String COMPRESSED_COBBLE = Mods.EXTRA_UTILITIES + ":CompressedCobblestone"; // public static final String CAPACITOR_BANK = Mods.ENDERIO + ":blockCapBank"; // } // }
import brightspark.sparkshammers.Reference; import net.minecraftforge.fml.common.FMLLog; import org.apache.logging.log4j.Level;
package brightspark.sparkshammers.util; // Class originally created by Pahimar public class LogHelper { public static void log(Level logLevel, Object object) {
// Path: src/main/java/brightspark/sparkshammers/Reference.java // public class Reference // { // public static final String MOD_ID = "sparkshammers"; // public static final String MOD_NAME = "Spark's Hammers"; // public static final String VERSION = "@VERSION@"; // public static final String DEPENDENCIES = // "after:enderio;" + // "after:botania;" + // "after:mobhunter;" + // "after:jei"; // // public static final String ITEM_TEXTURE_DIR = MOD_ID + ":"; // public static final String GUI_TEXTURE_DIR = "textures/gui/"; // public static final File CONFIG_DIR = new File(Loader.instance().getConfigDir(), MOD_ID); // // public static class JEI // { // public static final String HAMMER_CRAFTING_UID = MOD_ID + ":hammerCrafting"; // public static final String HAMMER_CRAFTING_TITLE_UNLOC = "jei.recipe.hammerCraftingTable"; // } // // public static class UUIDs // { // public static final UUID BRIGHT_SPARK = UUID.fromString("4adad317-d08b-412d-a75b-c2834386b088"); // public static final UUID _8BRICKDMG = UUID.fromString("647c557d-b494-45cf-9be9-f9774348d4c1"); // } // // public static class Items // { // public static final String HAMMER = "hammer"; // public static final String EXCAVATOR = "excavator"; // } // // public static class Mods // { // public static final String BOTANIA = "botania"; // public static final String EXTRA_UTILITIES = "extrautils2"; // public static final String ENDERIO = "enderio"; // } // // public static class ModItemIds // { // public static final String COMPRESSED_COBBLE = Mods.EXTRA_UTILITIES + ":CompressedCobblestone"; // public static final String CAPACITOR_BANK = Mods.ENDERIO + ":blockCapBank"; // } // } // Path: src/main/java/brightspark/sparkshammers/util/LogHelper.java import brightspark.sparkshammers.Reference; import net.minecraftforge.fml.common.FMLLog; import org.apache.logging.log4j.Level; package brightspark.sparkshammers.util; // Class originally created by Pahimar public class LogHelper { public static void log(Level logLevel, Object object) {
FMLLog.log(Reference.MOD_NAME, logLevel, Reference.MOD_NAME + ": " + String.valueOf(object));
thebrightspark/SparksHammers
src/main/java/brightspark/sparkshammers/gui/GuiContainerBase.java
// Path: src/main/java/brightspark/sparkshammers/Reference.java // public class Reference // { // public static final String MOD_ID = "sparkshammers"; // public static final String MOD_NAME = "Spark's Hammers"; // public static final String VERSION = "@VERSION@"; // public static final String DEPENDENCIES = // "after:enderio;" + // "after:botania;" + // "after:mobhunter;" + // "after:jei"; // // public static final String ITEM_TEXTURE_DIR = MOD_ID + ":"; // public static final String GUI_TEXTURE_DIR = "textures/gui/"; // public static final File CONFIG_DIR = new File(Loader.instance().getConfigDir(), MOD_ID); // // public static class JEI // { // public static final String HAMMER_CRAFTING_UID = MOD_ID + ":hammerCrafting"; // public static final String HAMMER_CRAFTING_TITLE_UNLOC = "jei.recipe.hammerCraftingTable"; // } // // public static class UUIDs // { // public static final UUID BRIGHT_SPARK = UUID.fromString("4adad317-d08b-412d-a75b-c2834386b088"); // public static final UUID _8BRICKDMG = UUID.fromString("647c557d-b494-45cf-9be9-f9774348d4c1"); // } // // public static class Items // { // public static final String HAMMER = "hammer"; // public static final String EXCAVATOR = "excavator"; // } // // public static class Mods // { // public static final String BOTANIA = "botania"; // public static final String EXTRA_UTILITIES = "extrautils2"; // public static final String ENDERIO = "enderio"; // } // // public static class ModItemIds // { // public static final String COMPRESSED_COBBLE = Mods.EXTRA_UTILITIES + ":CompressedCobblestone"; // public static final String CAPACITOR_BANK = Mods.ENDERIO + ":blockCapBank"; // } // }
import brightspark.sparkshammers.Reference; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.inventory.Container; import net.minecraft.util.ResourceLocation;
package brightspark.sparkshammers.gui; public abstract class GuiContainerBase<T extends Container> extends GuiContainer { private final ResourceLocation guiImage; protected T container; protected int textPlayerInvY = 82; protected int textColour = 4210752; public GuiContainerBase(T container, String guiName) { super(container); this.container = container;
// Path: src/main/java/brightspark/sparkshammers/Reference.java // public class Reference // { // public static final String MOD_ID = "sparkshammers"; // public static final String MOD_NAME = "Spark's Hammers"; // public static final String VERSION = "@VERSION@"; // public static final String DEPENDENCIES = // "after:enderio;" + // "after:botania;" + // "after:mobhunter;" + // "after:jei"; // // public static final String ITEM_TEXTURE_DIR = MOD_ID + ":"; // public static final String GUI_TEXTURE_DIR = "textures/gui/"; // public static final File CONFIG_DIR = new File(Loader.instance().getConfigDir(), MOD_ID); // // public static class JEI // { // public static final String HAMMER_CRAFTING_UID = MOD_ID + ":hammerCrafting"; // public static final String HAMMER_CRAFTING_TITLE_UNLOC = "jei.recipe.hammerCraftingTable"; // } // // public static class UUIDs // { // public static final UUID BRIGHT_SPARK = UUID.fromString("4adad317-d08b-412d-a75b-c2834386b088"); // public static final UUID _8BRICKDMG = UUID.fromString("647c557d-b494-45cf-9be9-f9774348d4c1"); // } // // public static class Items // { // public static final String HAMMER = "hammer"; // public static final String EXCAVATOR = "excavator"; // } // // public static class Mods // { // public static final String BOTANIA = "botania"; // public static final String EXTRA_UTILITIES = "extrautils2"; // public static final String ENDERIO = "enderio"; // } // // public static class ModItemIds // { // public static final String COMPRESSED_COBBLE = Mods.EXTRA_UTILITIES + ":CompressedCobblestone"; // public static final String CAPACITOR_BANK = Mods.ENDERIO + ":blockCapBank"; // } // } // Path: src/main/java/brightspark/sparkshammers/gui/GuiContainerBase.java import brightspark.sparkshammers.Reference; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.inventory.Container; import net.minecraft.util.ResourceLocation; package brightspark.sparkshammers.gui; public abstract class GuiContainerBase<T extends Container> extends GuiContainer { private final ResourceLocation guiImage; protected T container; protected int textPlayerInvY = 82; protected int textColour = 4210752; public GuiContainerBase(T container, String guiName) { super(container); this.container = container;
guiImage = new ResourceLocation(Reference.MOD_ID, Reference.GUI_TEXTURE_DIR + guiName + ".png");
thebrightspark/SparksHammers
src/main/java/brightspark/sparkshammers/gui/ContainerHammerCraft.java
// Path: src/main/java/brightspark/sparkshammers/hammerCrafting/HammerCraftingManager.java // public class HammerCraftingManager // { // public static IForgeRegistry<HammerShapedOreRecipe> REGISTRY; // // /** // * Returns the static instance of this class // */ // public static void setRegistry(IForgeRegistry<HammerShapedOreRecipe> registry) // { // REGISTRY = registry; // } // // public static List<HammerShapedOreRecipe> getRecipes() // { // return REGISTRY.getValues(); // } // // private HammerCraftingManager() {} // // public static ItemStack findMatchingRecipe(InventoryCrafting invCrafting) // { // for(HammerShapedOreRecipe recipe : REGISTRY) // if(recipe.matches(invCrafting)) // return recipe.getRecipeOutput(); // // return ItemStack.EMPTY; // } // // public static NonNullList<ItemStack> getRemainingItems(InventoryCrafting inv) // { // for (HammerShapedOreRecipe recipe : REGISTRY) // if (recipe.matches(inv)) // return recipe.getRemainingItems(inv); // return ForgeHooks.defaultRecipeGetRemainingItems(inv); // } // // /** // * Returns the list of all valid recipes which do not have any missing ingredients // * This is used by the JEI plugin // */ // public static List<HammerShapedOreRecipe> getValidRecipeList() // { // List<HammerShapedOreRecipe> validRecipes = Lists.newArrayList(); // for(HammerShapedOreRecipe recipe : REGISTRY) // { // String oreDic = ((ItemAOE) recipe.getRecipeOutput().getItem()).getDependantOreDic(); // if(oreDic == null || !OreDictionary.getOres(oreDic).isEmpty()) // validRecipes.add(recipe); // } // return validRecipes; // } // } // // Path: src/main/java/brightspark/sparkshammers/init/SHBlocks.java // public class SHBlocks // { // public static List<Block> BLOCKS; // public static List<ItemBlock> ITEM_BLOCKS; // // public static BlockHammer blockHammer = new BlockHammer(); // public static BlockHammerCraft blockHammerCraft = new BlockHammerCraft(); // // public static void addBlock(Block block) // { // BLOCKS.add(block); // ITEM_BLOCKS.add((ItemBlock) new ItemBlock(block).setRegistryName(block.getRegistryName())); // } // // private static void init() // { // BLOCKS = new ArrayList<>(); // ITEM_BLOCKS = new ArrayList<>(); // // addBlock(blockHammer); // addBlock(blockHammerCraft); // } // // public static Block[] getBlocks() // { // if(BLOCKS == null) init(); // return BLOCKS.toArray(new Block[0]); // } // // public static ItemBlock[] getItemBlocks() // { // if(ITEM_BLOCKS == null) init(); // return ITEM_BLOCKS.toArray(new ItemBlock[0]); // } // }
import brightspark.sparkshammers.hammerCrafting.HammerCraftingManager; import brightspark.sparkshammers.init.SHBlocks; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.init.Blocks; import net.minecraft.inventory.*; import net.minecraft.item.ItemStack; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World;
worldObj = world; pos = position; //Add the slots addSlotToContainer(new SlotSHCrafting(invPlayer.player, craftMatrix, craftResult, 0, resultX, resultY)); int handleXStart = gridStartX + 18 * 2; int handleYStart = gridStartY + 18 * 2; for(int headY = 0; headY <= 2; headY++) { for(int headX = 0; headX <= 4; headX++) { //Slot(IInventory, Slot Index, X Position, Y Position) if(headY == 2) { if(headX < 4) addSlotToContainer(new Slot(craftMatrix, numSlots, handleXStart, handleYStart + headX * 18)); } else addSlotToContainer(new Slot(craftMatrix, numSlots, gridStartX + headX * 18, gridStartY + headY * 18)); numSlots++; } } bindPlayerInventory(invPlayer); } @Override public void onCraftMatrixChanged(IInventory inventory) {
// Path: src/main/java/brightspark/sparkshammers/hammerCrafting/HammerCraftingManager.java // public class HammerCraftingManager // { // public static IForgeRegistry<HammerShapedOreRecipe> REGISTRY; // // /** // * Returns the static instance of this class // */ // public static void setRegistry(IForgeRegistry<HammerShapedOreRecipe> registry) // { // REGISTRY = registry; // } // // public static List<HammerShapedOreRecipe> getRecipes() // { // return REGISTRY.getValues(); // } // // private HammerCraftingManager() {} // // public static ItemStack findMatchingRecipe(InventoryCrafting invCrafting) // { // for(HammerShapedOreRecipe recipe : REGISTRY) // if(recipe.matches(invCrafting)) // return recipe.getRecipeOutput(); // // return ItemStack.EMPTY; // } // // public static NonNullList<ItemStack> getRemainingItems(InventoryCrafting inv) // { // for (HammerShapedOreRecipe recipe : REGISTRY) // if (recipe.matches(inv)) // return recipe.getRemainingItems(inv); // return ForgeHooks.defaultRecipeGetRemainingItems(inv); // } // // /** // * Returns the list of all valid recipes which do not have any missing ingredients // * This is used by the JEI plugin // */ // public static List<HammerShapedOreRecipe> getValidRecipeList() // { // List<HammerShapedOreRecipe> validRecipes = Lists.newArrayList(); // for(HammerShapedOreRecipe recipe : REGISTRY) // { // String oreDic = ((ItemAOE) recipe.getRecipeOutput().getItem()).getDependantOreDic(); // if(oreDic == null || !OreDictionary.getOres(oreDic).isEmpty()) // validRecipes.add(recipe); // } // return validRecipes; // } // } // // Path: src/main/java/brightspark/sparkshammers/init/SHBlocks.java // public class SHBlocks // { // public static List<Block> BLOCKS; // public static List<ItemBlock> ITEM_BLOCKS; // // public static BlockHammer blockHammer = new BlockHammer(); // public static BlockHammerCraft blockHammerCraft = new BlockHammerCraft(); // // public static void addBlock(Block block) // { // BLOCKS.add(block); // ITEM_BLOCKS.add((ItemBlock) new ItemBlock(block).setRegistryName(block.getRegistryName())); // } // // private static void init() // { // BLOCKS = new ArrayList<>(); // ITEM_BLOCKS = new ArrayList<>(); // // addBlock(blockHammer); // addBlock(blockHammerCraft); // } // // public static Block[] getBlocks() // { // if(BLOCKS == null) init(); // return BLOCKS.toArray(new Block[0]); // } // // public static ItemBlock[] getItemBlocks() // { // if(ITEM_BLOCKS == null) init(); // return ITEM_BLOCKS.toArray(new ItemBlock[0]); // } // } // Path: src/main/java/brightspark/sparkshammers/gui/ContainerHammerCraft.java import brightspark.sparkshammers.hammerCrafting.HammerCraftingManager; import brightspark.sparkshammers.init.SHBlocks; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.init.Blocks; import net.minecraft.inventory.*; import net.minecraft.item.ItemStack; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; worldObj = world; pos = position; //Add the slots addSlotToContainer(new SlotSHCrafting(invPlayer.player, craftMatrix, craftResult, 0, resultX, resultY)); int handleXStart = gridStartX + 18 * 2; int handleYStart = gridStartY + 18 * 2; for(int headY = 0; headY <= 2; headY++) { for(int headX = 0; headX <= 4; headX++) { //Slot(IInventory, Slot Index, X Position, Y Position) if(headY == 2) { if(headX < 4) addSlotToContainer(new Slot(craftMatrix, numSlots, handleXStart, handleYStart + headX * 18)); } else addSlotToContainer(new Slot(craftMatrix, numSlots, gridStartX + headX * 18, gridStartY + headY * 18)); numSlots++; } } bindPlayerInventory(invPlayer); } @Override public void onCraftMatrixChanged(IInventory inventory) {
ItemStack stack = HammerCraftingManager.findMatchingRecipe(craftMatrix);
thebrightspark/SparksHammers
src/main/java/brightspark/sparkshammers/gui/ContainerHammerCraft.java
// Path: src/main/java/brightspark/sparkshammers/hammerCrafting/HammerCraftingManager.java // public class HammerCraftingManager // { // public static IForgeRegistry<HammerShapedOreRecipe> REGISTRY; // // /** // * Returns the static instance of this class // */ // public static void setRegistry(IForgeRegistry<HammerShapedOreRecipe> registry) // { // REGISTRY = registry; // } // // public static List<HammerShapedOreRecipe> getRecipes() // { // return REGISTRY.getValues(); // } // // private HammerCraftingManager() {} // // public static ItemStack findMatchingRecipe(InventoryCrafting invCrafting) // { // for(HammerShapedOreRecipe recipe : REGISTRY) // if(recipe.matches(invCrafting)) // return recipe.getRecipeOutput(); // // return ItemStack.EMPTY; // } // // public static NonNullList<ItemStack> getRemainingItems(InventoryCrafting inv) // { // for (HammerShapedOreRecipe recipe : REGISTRY) // if (recipe.matches(inv)) // return recipe.getRemainingItems(inv); // return ForgeHooks.defaultRecipeGetRemainingItems(inv); // } // // /** // * Returns the list of all valid recipes which do not have any missing ingredients // * This is used by the JEI plugin // */ // public static List<HammerShapedOreRecipe> getValidRecipeList() // { // List<HammerShapedOreRecipe> validRecipes = Lists.newArrayList(); // for(HammerShapedOreRecipe recipe : REGISTRY) // { // String oreDic = ((ItemAOE) recipe.getRecipeOutput().getItem()).getDependantOreDic(); // if(oreDic == null || !OreDictionary.getOres(oreDic).isEmpty()) // validRecipes.add(recipe); // } // return validRecipes; // } // } // // Path: src/main/java/brightspark/sparkshammers/init/SHBlocks.java // public class SHBlocks // { // public static List<Block> BLOCKS; // public static List<ItemBlock> ITEM_BLOCKS; // // public static BlockHammer blockHammer = new BlockHammer(); // public static BlockHammerCraft blockHammerCraft = new BlockHammerCraft(); // // public static void addBlock(Block block) // { // BLOCKS.add(block); // ITEM_BLOCKS.add((ItemBlock) new ItemBlock(block).setRegistryName(block.getRegistryName())); // } // // private static void init() // { // BLOCKS = new ArrayList<>(); // ITEM_BLOCKS = new ArrayList<>(); // // addBlock(blockHammer); // addBlock(blockHammerCraft); // } // // public static Block[] getBlocks() // { // if(BLOCKS == null) init(); // return BLOCKS.toArray(new Block[0]); // } // // public static ItemBlock[] getItemBlocks() // { // if(ITEM_BLOCKS == null) init(); // return ITEM_BLOCKS.toArray(new ItemBlock[0]); // } // }
import brightspark.sparkshammers.hammerCrafting.HammerCraftingManager; import brightspark.sparkshammers.init.SHBlocks; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.init.Blocks; import net.minecraft.inventory.*; import net.minecraft.item.ItemStack; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World;
int handleYStart = gridStartY + 18 * 2; for(int headY = 0; headY <= 2; headY++) { for(int headX = 0; headX <= 4; headX++) { //Slot(IInventory, Slot Index, X Position, Y Position) if(headY == 2) { if(headX < 4) addSlotToContainer(new Slot(craftMatrix, numSlots, handleXStart, handleYStart + headX * 18)); } else addSlotToContainer(new Slot(craftMatrix, numSlots, gridStartX + headX * 18, gridStartY + headY * 18)); numSlots++; } } bindPlayerInventory(invPlayer); } @Override public void onCraftMatrixChanged(IInventory inventory) { ItemStack stack = HammerCraftingManager.findMatchingRecipe(craftMatrix); craftResult.setInventorySlotContents(0, stack); } public boolean canInteractWith(EntityPlayer player) { //Returns true if the block is the Hammer Crafting block, and is within range
// Path: src/main/java/brightspark/sparkshammers/hammerCrafting/HammerCraftingManager.java // public class HammerCraftingManager // { // public static IForgeRegistry<HammerShapedOreRecipe> REGISTRY; // // /** // * Returns the static instance of this class // */ // public static void setRegistry(IForgeRegistry<HammerShapedOreRecipe> registry) // { // REGISTRY = registry; // } // // public static List<HammerShapedOreRecipe> getRecipes() // { // return REGISTRY.getValues(); // } // // private HammerCraftingManager() {} // // public static ItemStack findMatchingRecipe(InventoryCrafting invCrafting) // { // for(HammerShapedOreRecipe recipe : REGISTRY) // if(recipe.matches(invCrafting)) // return recipe.getRecipeOutput(); // // return ItemStack.EMPTY; // } // // public static NonNullList<ItemStack> getRemainingItems(InventoryCrafting inv) // { // for (HammerShapedOreRecipe recipe : REGISTRY) // if (recipe.matches(inv)) // return recipe.getRemainingItems(inv); // return ForgeHooks.defaultRecipeGetRemainingItems(inv); // } // // /** // * Returns the list of all valid recipes which do not have any missing ingredients // * This is used by the JEI plugin // */ // public static List<HammerShapedOreRecipe> getValidRecipeList() // { // List<HammerShapedOreRecipe> validRecipes = Lists.newArrayList(); // for(HammerShapedOreRecipe recipe : REGISTRY) // { // String oreDic = ((ItemAOE) recipe.getRecipeOutput().getItem()).getDependantOreDic(); // if(oreDic == null || !OreDictionary.getOres(oreDic).isEmpty()) // validRecipes.add(recipe); // } // return validRecipes; // } // } // // Path: src/main/java/brightspark/sparkshammers/init/SHBlocks.java // public class SHBlocks // { // public static List<Block> BLOCKS; // public static List<ItemBlock> ITEM_BLOCKS; // // public static BlockHammer blockHammer = new BlockHammer(); // public static BlockHammerCraft blockHammerCraft = new BlockHammerCraft(); // // public static void addBlock(Block block) // { // BLOCKS.add(block); // ITEM_BLOCKS.add((ItemBlock) new ItemBlock(block).setRegistryName(block.getRegistryName())); // } // // private static void init() // { // BLOCKS = new ArrayList<>(); // ITEM_BLOCKS = new ArrayList<>(); // // addBlock(blockHammer); // addBlock(blockHammerCraft); // } // // public static Block[] getBlocks() // { // if(BLOCKS == null) init(); // return BLOCKS.toArray(new Block[0]); // } // // public static ItemBlock[] getItemBlocks() // { // if(ITEM_BLOCKS == null) init(); // return ITEM_BLOCKS.toArray(new ItemBlock[0]); // } // } // Path: src/main/java/brightspark/sparkshammers/gui/ContainerHammerCraft.java import brightspark.sparkshammers.hammerCrafting.HammerCraftingManager; import brightspark.sparkshammers.init.SHBlocks; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.init.Blocks; import net.minecraft.inventory.*; import net.minecraft.item.ItemStack; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; int handleYStart = gridStartY + 18 * 2; for(int headY = 0; headY <= 2; headY++) { for(int headX = 0; headX <= 4; headX++) { //Slot(IInventory, Slot Index, X Position, Y Position) if(headY == 2) { if(headX < 4) addSlotToContainer(new Slot(craftMatrix, numSlots, handleXStart, handleYStart + headX * 18)); } else addSlotToContainer(new Slot(craftMatrix, numSlots, gridStartX + headX * 18, gridStartY + headY * 18)); numSlots++; } } bindPlayerInventory(invPlayer); } @Override public void onCraftMatrixChanged(IInventory inventory) { ItemStack stack = HammerCraftingManager.findMatchingRecipe(craftMatrix); craftResult.setInventorySlotContents(0, stack); } public boolean canInteractWith(EntityPlayer player) { //Returns true if the block is the Hammer Crafting block, and is within range
return worldObj.getBlockState(pos).getBlock() == SHBlocks.blockHammerCraft && player.getDistanceSq((double)pos.getX() + 0.5D, (double)pos.getY() + 0.5D, (double)pos.getZ() + 0.5D) <= 64.0D;
thebrightspark/SparksHammers
src/main/java/brightspark/sparkshammers/handlers/MiningObject.java
// Path: src/main/java/brightspark/sparkshammers/item/ItemHammerNetherStar.java // public class ItemHammerNetherStar extends ItemAOE // { // public ItemHammerNetherStar(Tool tool) // { // super(tool, false); // } // // @Override // protected boolean shouldShowInCreativeTabs() // { // return true; // } // // @SideOnly(Side.CLIENT) // @Override // public boolean hasEffect(ItemStack stack) // { // return true; // } // // @Override // public boolean hitEntity(ItemStack stack, EntityLivingBase entityHit, EntityLivingBase player) // { // //Damages hammer for 1 tunnel mining use // stack.damageItem(1, entityHit); // return true; // } // // //Overriding this to stop item damage which is handled elsewhere // @Override // public boolean onBlockDestroyed(ItemStack stack, World worldIn, IBlockState state, BlockPos pos, EntityLivingBase entityLiving) // { // return true; // } // // @Override // public boolean onBlockStartBreak(ItemStack stack, BlockPos pos, EntityPlayer player) // { // //Can only mine when the NBT tag isn't true // if(NBTHelper.getBoolean(stack, "mining")) return true; // return super.onBlockStartBreak(stack, pos, player); // } // }
import brightspark.sparkshammers.item.ItemHammerNetherStar; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraftforge.common.ForgeHooks;
package brightspark.sparkshammers.handlers; public class MiningObject { public World world; public EntityPlayer player; public ItemStack stackActual, stackCopy; public EnumFacing facing; public BlockPos hitPos; public float blockStrength; public int iteration; public MiningObject(EntityPlayer player, BlockPos hitPos, IBlockState state) { world = player.world; this.player = player; stackActual = player.getHeldItemMainhand(); stackCopy = stackActual.copy();
// Path: src/main/java/brightspark/sparkshammers/item/ItemHammerNetherStar.java // public class ItemHammerNetherStar extends ItemAOE // { // public ItemHammerNetherStar(Tool tool) // { // super(tool, false); // } // // @Override // protected boolean shouldShowInCreativeTabs() // { // return true; // } // // @SideOnly(Side.CLIENT) // @Override // public boolean hasEffect(ItemStack stack) // { // return true; // } // // @Override // public boolean hitEntity(ItemStack stack, EntityLivingBase entityHit, EntityLivingBase player) // { // //Damages hammer for 1 tunnel mining use // stack.damageItem(1, entityHit); // return true; // } // // //Overriding this to stop item damage which is handled elsewhere // @Override // public boolean onBlockDestroyed(ItemStack stack, World worldIn, IBlockState state, BlockPos pos, EntityLivingBase entityLiving) // { // return true; // } // // @Override // public boolean onBlockStartBreak(ItemStack stack, BlockPos pos, EntityPlayer player) // { // //Can only mine when the NBT tag isn't true // if(NBTHelper.getBoolean(stack, "mining")) return true; // return super.onBlockStartBreak(stack, pos, player); // } // } // Path: src/main/java/brightspark/sparkshammers/handlers/MiningObject.java import brightspark.sparkshammers.item.ItemHammerNetherStar; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraftforge.common.ForgeHooks; package brightspark.sparkshammers.handlers; public class MiningObject { public World world; public EntityPlayer player; public ItemStack stackActual, stackCopy; public EnumFacing facing; public BlockPos hitPos; public float blockStrength; public int iteration; public MiningObject(EntityPlayer player, BlockPos hitPos, IBlockState state) { world = player.world; this.player = player; stackActual = player.getHeldItemMainhand(); stackCopy = stackActual.copy();
facing = ((ItemHammerNetherStar) stackActual.getItem()).rayTrace(world, player, false).sideHit.getOpposite();
thebrightspark/SparksHammers
src/main/java/brightspark/sparkshammers/worldgen/WorldGenMjolnirShrine.java
// Path: src/main/java/brightspark/sparkshammers/SHConfig.java // @Config(modid = Reference.MOD_ID, name = Reference.MOD_ID + "/config") // @Config.LangKey(Reference.MOD_ID + ".title") // public class SHConfig // { // @Config.Comment("Set this to true to enable right clicking with tools to place torches from the player's inventory") // public static boolean rightClickPlacesTorches = false; // // @Config.Comment("The depth which the Nether Star Hammer will destroy") // @Config.RangeInt(min = 1) // public static int netherStarHammerDistance = 16; // // @Config.Comment("Powered Hammer configs") // public static final Powered POWERED = new Powered(); // // @Config.Comment("Mjolnir configs") // public static final Mjolnir MJOLNIR = new Mjolnir(); // // public static class Powered // { // @Config.Comment("The energy capacity of powered tools") // @Config.RequiresMcRestart // public int poweredEnergyCapacity = 100000; // // @Config.Comment("How much energy powered tools will use per block destroyed (Hitting entities will use x2 this amount)") // @Config.RequiresMcRestart // public int poweredEnergyUsePerBlock = 100; // // @Config.Comment("The rate at which you can fill the energy of powered tools, in energy per tick") // @Config.RequiresMcRestart // public int poweredEnergyInputRate = 10000; // } // // public static class Mjolnir // { // @Config.Comment("Whether shrine structures should be generated in the world to find Mjolnir in") // @Config.RequiresMcRestart // public boolean shouldGenerateMjolnirShrines = true; // // @Config.Comment("Chance of a shrine spawning (Higher is less chance)") // public int mjolnirShrineRarity = 50; // // @Config.Comment("Minimum Y coordinate value for the shrine to spawn at") // public int mjolnirShrineMinY = 125; // // @Config.Comment("When true, a log will be printed in the console every time a shrine is generated with it's coordinates") // public boolean mjolnirShrineDebug = false; // // @Config.Comment("Whether Mjolnir needs the player to have the \"end/kill_dragon\" advancement to be 'worthy'") // public boolean mjolnirPickupNeedsDragonAchieve = true; // } // } // // Path: src/main/java/brightspark/sparkshammers/init/SHBlocks.java // public class SHBlocks // { // public static List<Block> BLOCKS; // public static List<ItemBlock> ITEM_BLOCKS; // // public static BlockHammer blockHammer = new BlockHammer(); // public static BlockHammerCraft blockHammerCraft = new BlockHammerCraft(); // // public static void addBlock(Block block) // { // BLOCKS.add(block); // ITEM_BLOCKS.add((ItemBlock) new ItemBlock(block).setRegistryName(block.getRegistryName())); // } // // private static void init() // { // BLOCKS = new ArrayList<>(); // ITEM_BLOCKS = new ArrayList<>(); // // addBlock(blockHammer); // addBlock(blockHammerCraft); // } // // public static Block[] getBlocks() // { // if(BLOCKS == null) init(); // return BLOCKS.toArray(new Block[0]); // } // // public static ItemBlock[] getItemBlocks() // { // if(ITEM_BLOCKS == null) init(); // return ITEM_BLOCKS.toArray(new ItemBlock[0]); // } // } // // Path: src/main/java/brightspark/sparkshammers/util/LogHelper.java // public class LogHelper // { // public static void log(Level logLevel, Object object) // { // FMLLog.log(Reference.MOD_NAME, logLevel, Reference.MOD_NAME + ": " + String.valueOf(object)); // } // // public static void all(Object object) // { // log(Level.ALL, object); // } // // public static void debug(Object object) // { // log(Level.DEBUG, object); // } // // public static void error(Object object) // { // log(Level.ERROR, object); // } // // public static void fatal(Object object) // { // log(Level.FATAL, object); // } // // public static void info(Object object) // { // log(Level.INFO, object); // } // // public static void off(Object object) // { // log(Level.OFF, object); // } // // public static void trace(Object object) // { // log(Level.TRACE, object); // } // // public static void warn(Object object) // { // log(Level.WARN, object); // } // }
import brightspark.sparkshammers.SHConfig; import brightspark.sparkshammers.init.SHBlocks; import brightspark.sparkshammers.util.LogHelper; import net.minecraft.block.*; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; import net.minecraft.item.EnumDyeColor; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraft.world.chunk.IChunkProvider; import net.minecraft.world.gen.IChunkGenerator; import net.minecraftforge.fml.common.IWorldGenerator; import java.util.Random;
package brightspark.sparkshammers.worldgen; public class WorldGenMjolnirShrine implements IWorldGenerator { @Override public void generate(Random random, int chunkX, int chunkZ, World world, IChunkGenerator chunkGenerator, IChunkProvider chunkProvider) { //ID for the overworld == 0 if(world.provider.getDimension() == 0) { //Get the surface position with a random coord in the given chunk BlockPos pos = world.getTopSolidOrLiquidBlock(new BlockPos(chunkX * 16 + random.nextInt(5), 1, chunkZ * 16 + random.nextInt(5))); int posY = isValidSpawn(world, pos);
// Path: src/main/java/brightspark/sparkshammers/SHConfig.java // @Config(modid = Reference.MOD_ID, name = Reference.MOD_ID + "/config") // @Config.LangKey(Reference.MOD_ID + ".title") // public class SHConfig // { // @Config.Comment("Set this to true to enable right clicking with tools to place torches from the player's inventory") // public static boolean rightClickPlacesTorches = false; // // @Config.Comment("The depth which the Nether Star Hammer will destroy") // @Config.RangeInt(min = 1) // public static int netherStarHammerDistance = 16; // // @Config.Comment("Powered Hammer configs") // public static final Powered POWERED = new Powered(); // // @Config.Comment("Mjolnir configs") // public static final Mjolnir MJOLNIR = new Mjolnir(); // // public static class Powered // { // @Config.Comment("The energy capacity of powered tools") // @Config.RequiresMcRestart // public int poweredEnergyCapacity = 100000; // // @Config.Comment("How much energy powered tools will use per block destroyed (Hitting entities will use x2 this amount)") // @Config.RequiresMcRestart // public int poweredEnergyUsePerBlock = 100; // // @Config.Comment("The rate at which you can fill the energy of powered tools, in energy per tick") // @Config.RequiresMcRestart // public int poweredEnergyInputRate = 10000; // } // // public static class Mjolnir // { // @Config.Comment("Whether shrine structures should be generated in the world to find Mjolnir in") // @Config.RequiresMcRestart // public boolean shouldGenerateMjolnirShrines = true; // // @Config.Comment("Chance of a shrine spawning (Higher is less chance)") // public int mjolnirShrineRarity = 50; // // @Config.Comment("Minimum Y coordinate value for the shrine to spawn at") // public int mjolnirShrineMinY = 125; // // @Config.Comment("When true, a log will be printed in the console every time a shrine is generated with it's coordinates") // public boolean mjolnirShrineDebug = false; // // @Config.Comment("Whether Mjolnir needs the player to have the \"end/kill_dragon\" advancement to be 'worthy'") // public boolean mjolnirPickupNeedsDragonAchieve = true; // } // } // // Path: src/main/java/brightspark/sparkshammers/init/SHBlocks.java // public class SHBlocks // { // public static List<Block> BLOCKS; // public static List<ItemBlock> ITEM_BLOCKS; // // public static BlockHammer blockHammer = new BlockHammer(); // public static BlockHammerCraft blockHammerCraft = new BlockHammerCraft(); // // public static void addBlock(Block block) // { // BLOCKS.add(block); // ITEM_BLOCKS.add((ItemBlock) new ItemBlock(block).setRegistryName(block.getRegistryName())); // } // // private static void init() // { // BLOCKS = new ArrayList<>(); // ITEM_BLOCKS = new ArrayList<>(); // // addBlock(blockHammer); // addBlock(blockHammerCraft); // } // // public static Block[] getBlocks() // { // if(BLOCKS == null) init(); // return BLOCKS.toArray(new Block[0]); // } // // public static ItemBlock[] getItemBlocks() // { // if(ITEM_BLOCKS == null) init(); // return ITEM_BLOCKS.toArray(new ItemBlock[0]); // } // } // // Path: src/main/java/brightspark/sparkshammers/util/LogHelper.java // public class LogHelper // { // public static void log(Level logLevel, Object object) // { // FMLLog.log(Reference.MOD_NAME, logLevel, Reference.MOD_NAME + ": " + String.valueOf(object)); // } // // public static void all(Object object) // { // log(Level.ALL, object); // } // // public static void debug(Object object) // { // log(Level.DEBUG, object); // } // // public static void error(Object object) // { // log(Level.ERROR, object); // } // // public static void fatal(Object object) // { // log(Level.FATAL, object); // } // // public static void info(Object object) // { // log(Level.INFO, object); // } // // public static void off(Object object) // { // log(Level.OFF, object); // } // // public static void trace(Object object) // { // log(Level.TRACE, object); // } // // public static void warn(Object object) // { // log(Level.WARN, object); // } // } // Path: src/main/java/brightspark/sparkshammers/worldgen/WorldGenMjolnirShrine.java import brightspark.sparkshammers.SHConfig; import brightspark.sparkshammers.init.SHBlocks; import brightspark.sparkshammers.util.LogHelper; import net.minecraft.block.*; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; import net.minecraft.item.EnumDyeColor; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraft.world.chunk.IChunkProvider; import net.minecraft.world.gen.IChunkGenerator; import net.minecraftforge.fml.common.IWorldGenerator; import java.util.Random; package brightspark.sparkshammers.worldgen; public class WorldGenMjolnirShrine implements IWorldGenerator { @Override public void generate(Random random, int chunkX, int chunkZ, World world, IChunkGenerator chunkGenerator, IChunkProvider chunkProvider) { //ID for the overworld == 0 if(world.provider.getDimension() == 0) { //Get the surface position with a random coord in the given chunk BlockPos pos = world.getTopSolidOrLiquidBlock(new BlockPos(chunkX * 16 + random.nextInt(5), 1, chunkZ * 16 + random.nextInt(5))); int posY = isValidSpawn(world, pos);
if(posY > 0 && random.nextInt(SHConfig.MJOLNIR.mjolnirShrineRarity) == 0)
thebrightspark/SparksHammers
src/main/java/brightspark/sparkshammers/worldgen/WorldGenMjolnirShrine.java
// Path: src/main/java/brightspark/sparkshammers/SHConfig.java // @Config(modid = Reference.MOD_ID, name = Reference.MOD_ID + "/config") // @Config.LangKey(Reference.MOD_ID + ".title") // public class SHConfig // { // @Config.Comment("Set this to true to enable right clicking with tools to place torches from the player's inventory") // public static boolean rightClickPlacesTorches = false; // // @Config.Comment("The depth which the Nether Star Hammer will destroy") // @Config.RangeInt(min = 1) // public static int netherStarHammerDistance = 16; // // @Config.Comment("Powered Hammer configs") // public static final Powered POWERED = new Powered(); // // @Config.Comment("Mjolnir configs") // public static final Mjolnir MJOLNIR = new Mjolnir(); // // public static class Powered // { // @Config.Comment("The energy capacity of powered tools") // @Config.RequiresMcRestart // public int poweredEnergyCapacity = 100000; // // @Config.Comment("How much energy powered tools will use per block destroyed (Hitting entities will use x2 this amount)") // @Config.RequiresMcRestart // public int poweredEnergyUsePerBlock = 100; // // @Config.Comment("The rate at which you can fill the energy of powered tools, in energy per tick") // @Config.RequiresMcRestart // public int poweredEnergyInputRate = 10000; // } // // public static class Mjolnir // { // @Config.Comment("Whether shrine structures should be generated in the world to find Mjolnir in") // @Config.RequiresMcRestart // public boolean shouldGenerateMjolnirShrines = true; // // @Config.Comment("Chance of a shrine spawning (Higher is less chance)") // public int mjolnirShrineRarity = 50; // // @Config.Comment("Minimum Y coordinate value for the shrine to spawn at") // public int mjolnirShrineMinY = 125; // // @Config.Comment("When true, a log will be printed in the console every time a shrine is generated with it's coordinates") // public boolean mjolnirShrineDebug = false; // // @Config.Comment("Whether Mjolnir needs the player to have the \"end/kill_dragon\" advancement to be 'worthy'") // public boolean mjolnirPickupNeedsDragonAchieve = true; // } // } // // Path: src/main/java/brightspark/sparkshammers/init/SHBlocks.java // public class SHBlocks // { // public static List<Block> BLOCKS; // public static List<ItemBlock> ITEM_BLOCKS; // // public static BlockHammer blockHammer = new BlockHammer(); // public static BlockHammerCraft blockHammerCraft = new BlockHammerCraft(); // // public static void addBlock(Block block) // { // BLOCKS.add(block); // ITEM_BLOCKS.add((ItemBlock) new ItemBlock(block).setRegistryName(block.getRegistryName())); // } // // private static void init() // { // BLOCKS = new ArrayList<>(); // ITEM_BLOCKS = new ArrayList<>(); // // addBlock(blockHammer); // addBlock(blockHammerCraft); // } // // public static Block[] getBlocks() // { // if(BLOCKS == null) init(); // return BLOCKS.toArray(new Block[0]); // } // // public static ItemBlock[] getItemBlocks() // { // if(ITEM_BLOCKS == null) init(); // return ITEM_BLOCKS.toArray(new ItemBlock[0]); // } // } // // Path: src/main/java/brightspark/sparkshammers/util/LogHelper.java // public class LogHelper // { // public static void log(Level logLevel, Object object) // { // FMLLog.log(Reference.MOD_NAME, logLevel, Reference.MOD_NAME + ": " + String.valueOf(object)); // } // // public static void all(Object object) // { // log(Level.ALL, object); // } // // public static void debug(Object object) // { // log(Level.DEBUG, object); // } // // public static void error(Object object) // { // log(Level.ERROR, object); // } // // public static void fatal(Object object) // { // log(Level.FATAL, object); // } // // public static void info(Object object) // { // log(Level.INFO, object); // } // // public static void off(Object object) // { // log(Level.OFF, object); // } // // public static void trace(Object object) // { // log(Level.TRACE, object); // } // // public static void warn(Object object) // { // log(Level.WARN, object); // } // }
import brightspark.sparkshammers.SHConfig; import brightspark.sparkshammers.init.SHBlocks; import brightspark.sparkshammers.util.LogHelper; import net.minecraft.block.*; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; import net.minecraft.item.EnumDyeColor; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraft.world.chunk.IChunkProvider; import net.minecraft.world.gen.IChunkGenerator; import net.minecraftforge.fml.common.IWorldGenerator; import java.util.Random;
package brightspark.sparkshammers.worldgen; public class WorldGenMjolnirShrine implements IWorldGenerator { @Override public void generate(Random random, int chunkX, int chunkZ, World world, IChunkGenerator chunkGenerator, IChunkProvider chunkProvider) { //ID for the overworld == 0 if(world.provider.getDimension() == 0) { //Get the surface position with a random coord in the given chunk BlockPos pos = world.getTopSolidOrLiquidBlock(new BlockPos(chunkX * 16 + random.nextInt(5), 1, chunkZ * 16 + random.nextInt(5))); int posY = isValidSpawn(world, pos); if(posY > 0 && random.nextInt(SHConfig.MJOLNIR.mjolnirShrineRarity) == 0) { //Clear the trees around the area if there are any clearTrees(world, pos.add(5, 0, 5), 10); //Generate the shrine generateShrine(world, pos); if(SHConfig.MJOLNIR.mjolnirShrineDebug)
// Path: src/main/java/brightspark/sparkshammers/SHConfig.java // @Config(modid = Reference.MOD_ID, name = Reference.MOD_ID + "/config") // @Config.LangKey(Reference.MOD_ID + ".title") // public class SHConfig // { // @Config.Comment("Set this to true to enable right clicking with tools to place torches from the player's inventory") // public static boolean rightClickPlacesTorches = false; // // @Config.Comment("The depth which the Nether Star Hammer will destroy") // @Config.RangeInt(min = 1) // public static int netherStarHammerDistance = 16; // // @Config.Comment("Powered Hammer configs") // public static final Powered POWERED = new Powered(); // // @Config.Comment("Mjolnir configs") // public static final Mjolnir MJOLNIR = new Mjolnir(); // // public static class Powered // { // @Config.Comment("The energy capacity of powered tools") // @Config.RequiresMcRestart // public int poweredEnergyCapacity = 100000; // // @Config.Comment("How much energy powered tools will use per block destroyed (Hitting entities will use x2 this amount)") // @Config.RequiresMcRestart // public int poweredEnergyUsePerBlock = 100; // // @Config.Comment("The rate at which you can fill the energy of powered tools, in energy per tick") // @Config.RequiresMcRestart // public int poweredEnergyInputRate = 10000; // } // // public static class Mjolnir // { // @Config.Comment("Whether shrine structures should be generated in the world to find Mjolnir in") // @Config.RequiresMcRestart // public boolean shouldGenerateMjolnirShrines = true; // // @Config.Comment("Chance of a shrine spawning (Higher is less chance)") // public int mjolnirShrineRarity = 50; // // @Config.Comment("Minimum Y coordinate value for the shrine to spawn at") // public int mjolnirShrineMinY = 125; // // @Config.Comment("When true, a log will be printed in the console every time a shrine is generated with it's coordinates") // public boolean mjolnirShrineDebug = false; // // @Config.Comment("Whether Mjolnir needs the player to have the \"end/kill_dragon\" advancement to be 'worthy'") // public boolean mjolnirPickupNeedsDragonAchieve = true; // } // } // // Path: src/main/java/brightspark/sparkshammers/init/SHBlocks.java // public class SHBlocks // { // public static List<Block> BLOCKS; // public static List<ItemBlock> ITEM_BLOCKS; // // public static BlockHammer blockHammer = new BlockHammer(); // public static BlockHammerCraft blockHammerCraft = new BlockHammerCraft(); // // public static void addBlock(Block block) // { // BLOCKS.add(block); // ITEM_BLOCKS.add((ItemBlock) new ItemBlock(block).setRegistryName(block.getRegistryName())); // } // // private static void init() // { // BLOCKS = new ArrayList<>(); // ITEM_BLOCKS = new ArrayList<>(); // // addBlock(blockHammer); // addBlock(blockHammerCraft); // } // // public static Block[] getBlocks() // { // if(BLOCKS == null) init(); // return BLOCKS.toArray(new Block[0]); // } // // public static ItemBlock[] getItemBlocks() // { // if(ITEM_BLOCKS == null) init(); // return ITEM_BLOCKS.toArray(new ItemBlock[0]); // } // } // // Path: src/main/java/brightspark/sparkshammers/util/LogHelper.java // public class LogHelper // { // public static void log(Level logLevel, Object object) // { // FMLLog.log(Reference.MOD_NAME, logLevel, Reference.MOD_NAME + ": " + String.valueOf(object)); // } // // public static void all(Object object) // { // log(Level.ALL, object); // } // // public static void debug(Object object) // { // log(Level.DEBUG, object); // } // // public static void error(Object object) // { // log(Level.ERROR, object); // } // // public static void fatal(Object object) // { // log(Level.FATAL, object); // } // // public static void info(Object object) // { // log(Level.INFO, object); // } // // public static void off(Object object) // { // log(Level.OFF, object); // } // // public static void trace(Object object) // { // log(Level.TRACE, object); // } // // public static void warn(Object object) // { // log(Level.WARN, object); // } // } // Path: src/main/java/brightspark/sparkshammers/worldgen/WorldGenMjolnirShrine.java import brightspark.sparkshammers.SHConfig; import brightspark.sparkshammers.init.SHBlocks; import brightspark.sparkshammers.util.LogHelper; import net.minecraft.block.*; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; import net.minecraft.item.EnumDyeColor; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraft.world.chunk.IChunkProvider; import net.minecraft.world.gen.IChunkGenerator; import net.minecraftforge.fml.common.IWorldGenerator; import java.util.Random; package brightspark.sparkshammers.worldgen; public class WorldGenMjolnirShrine implements IWorldGenerator { @Override public void generate(Random random, int chunkX, int chunkZ, World world, IChunkGenerator chunkGenerator, IChunkProvider chunkProvider) { //ID for the overworld == 0 if(world.provider.getDimension() == 0) { //Get the surface position with a random coord in the given chunk BlockPos pos = world.getTopSolidOrLiquidBlock(new BlockPos(chunkX * 16 + random.nextInt(5), 1, chunkZ * 16 + random.nextInt(5))); int posY = isValidSpawn(world, pos); if(posY > 0 && random.nextInt(SHConfig.MJOLNIR.mjolnirShrineRarity) == 0) { //Clear the trees around the area if there are any clearTrees(world, pos.add(5, 0, 5), 10); //Generate the shrine generateShrine(world, pos); if(SHConfig.MJOLNIR.mjolnirShrineDebug)
LogHelper.info("Mjolnir Shrine generated at: " + pos.add(5, 0, 5).toString());
thebrightspark/SparksHammers
src/main/java/brightspark/sparkshammers/integration/jei/HammerCraftingTable/HammerCraftingRecipeCategory.java
// Path: src/main/java/brightspark/sparkshammers/Reference.java // public class Reference // { // public static final String MOD_ID = "sparkshammers"; // public static final String MOD_NAME = "Spark's Hammers"; // public static final String VERSION = "@VERSION@"; // public static final String DEPENDENCIES = // "after:enderio;" + // "after:botania;" + // "after:mobhunter;" + // "after:jei"; // // public static final String ITEM_TEXTURE_DIR = MOD_ID + ":"; // public static final String GUI_TEXTURE_DIR = "textures/gui/"; // public static final File CONFIG_DIR = new File(Loader.instance().getConfigDir(), MOD_ID); // // public static class JEI // { // public static final String HAMMER_CRAFTING_UID = MOD_ID + ":hammerCrafting"; // public static final String HAMMER_CRAFTING_TITLE_UNLOC = "jei.recipe.hammerCraftingTable"; // } // // public static class UUIDs // { // public static final UUID BRIGHT_SPARK = UUID.fromString("4adad317-d08b-412d-a75b-c2834386b088"); // public static final UUID _8BRICKDMG = UUID.fromString("647c557d-b494-45cf-9be9-f9774348d4c1"); // } // // public static class Items // { // public static final String HAMMER = "hammer"; // public static final String EXCAVATOR = "excavator"; // } // // public static class Mods // { // public static final String BOTANIA = "botania"; // public static final String EXTRA_UTILITIES = "extrautils2"; // public static final String ENDERIO = "enderio"; // } // // public static class ModItemIds // { // public static final String COMPRESSED_COBBLE = Mods.EXTRA_UTILITIES + ":CompressedCobblestone"; // public static final String CAPACITOR_BANK = Mods.ENDERIO + ":blockCapBank"; // } // }
import brightspark.sparkshammers.Reference; import mezz.jei.api.IGuiHelper; import mezz.jei.api.gui.IDrawable; import mezz.jei.api.gui.IGuiItemStackGroup; import mezz.jei.api.gui.IRecipeLayout; import mezz.jei.api.ingredients.IIngredients; import mezz.jei.api.recipe.IRecipeCategory; import mezz.jei.api.recipe.IRecipeWrapper; import net.minecraft.client.Minecraft; import net.minecraft.client.resources.I18n; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import javax.annotation.Nonnull; import javax.annotation.Nullable;
package brightspark.sparkshammers.integration.jei.HammerCraftingTable; public class HammerCraftingRecipeCategory implements IRecipeCategory { private final String locTitle; private final IDrawable background; public HammerCraftingRecipeCategory(IGuiHelper guiHelper) {
// Path: src/main/java/brightspark/sparkshammers/Reference.java // public class Reference // { // public static final String MOD_ID = "sparkshammers"; // public static final String MOD_NAME = "Spark's Hammers"; // public static final String VERSION = "@VERSION@"; // public static final String DEPENDENCIES = // "after:enderio;" + // "after:botania;" + // "after:mobhunter;" + // "after:jei"; // // public static final String ITEM_TEXTURE_DIR = MOD_ID + ":"; // public static final String GUI_TEXTURE_DIR = "textures/gui/"; // public static final File CONFIG_DIR = new File(Loader.instance().getConfigDir(), MOD_ID); // // public static class JEI // { // public static final String HAMMER_CRAFTING_UID = MOD_ID + ":hammerCrafting"; // public static final String HAMMER_CRAFTING_TITLE_UNLOC = "jei.recipe.hammerCraftingTable"; // } // // public static class UUIDs // { // public static final UUID BRIGHT_SPARK = UUID.fromString("4adad317-d08b-412d-a75b-c2834386b088"); // public static final UUID _8BRICKDMG = UUID.fromString("647c557d-b494-45cf-9be9-f9774348d4c1"); // } // // public static class Items // { // public static final String HAMMER = "hammer"; // public static final String EXCAVATOR = "excavator"; // } // // public static class Mods // { // public static final String BOTANIA = "botania"; // public static final String EXTRA_UTILITIES = "extrautils2"; // public static final String ENDERIO = "enderio"; // } // // public static class ModItemIds // { // public static final String COMPRESSED_COBBLE = Mods.EXTRA_UTILITIES + ":CompressedCobblestone"; // public static final String CAPACITOR_BANK = Mods.ENDERIO + ":blockCapBank"; // } // } // Path: src/main/java/brightspark/sparkshammers/integration/jei/HammerCraftingTable/HammerCraftingRecipeCategory.java import brightspark.sparkshammers.Reference; import mezz.jei.api.IGuiHelper; import mezz.jei.api.gui.IDrawable; import mezz.jei.api.gui.IGuiItemStackGroup; import mezz.jei.api.gui.IRecipeLayout; import mezz.jei.api.ingredients.IIngredients; import mezz.jei.api.recipe.IRecipeCategory; import mezz.jei.api.recipe.IRecipeWrapper; import net.minecraft.client.Minecraft; import net.minecraft.client.resources.I18n; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import javax.annotation.Nonnull; import javax.annotation.Nullable; package brightspark.sparkshammers.integration.jei.HammerCraftingTable; public class HammerCraftingRecipeCategory implements IRecipeCategory { private final String locTitle; private final IDrawable background; public HammerCraftingRecipeCategory(IGuiHelper guiHelper) {
locTitle = I18n.format(Reference.JEI.HAMMER_CRAFTING_TITLE_UNLOC);
thebrightspark/SparksHammers
src/main/java/brightspark/sparkshammers/gui/SlotSHCrafting.java
// Path: src/main/java/brightspark/sparkshammers/hammerCrafting/HammerCraftingManager.java // public class HammerCraftingManager // { // public static IForgeRegistry<HammerShapedOreRecipe> REGISTRY; // // /** // * Returns the static instance of this class // */ // public static void setRegistry(IForgeRegistry<HammerShapedOreRecipe> registry) // { // REGISTRY = registry; // } // // public static List<HammerShapedOreRecipe> getRecipes() // { // return REGISTRY.getValues(); // } // // private HammerCraftingManager() {} // // public static ItemStack findMatchingRecipe(InventoryCrafting invCrafting) // { // for(HammerShapedOreRecipe recipe : REGISTRY) // if(recipe.matches(invCrafting)) // return recipe.getRecipeOutput(); // // return ItemStack.EMPTY; // } // // public static NonNullList<ItemStack> getRemainingItems(InventoryCrafting inv) // { // for (HammerShapedOreRecipe recipe : REGISTRY) // if (recipe.matches(inv)) // return recipe.getRemainingItems(inv); // return ForgeHooks.defaultRecipeGetRemainingItems(inv); // } // // /** // * Returns the list of all valid recipes which do not have any missing ingredients // * This is used by the JEI plugin // */ // public static List<HammerShapedOreRecipe> getValidRecipeList() // { // List<HammerShapedOreRecipe> validRecipes = Lists.newArrayList(); // for(HammerShapedOreRecipe recipe : REGISTRY) // { // String oreDic = ((ItemAOE) recipe.getRecipeOutput().getItem()).getDependantOreDic(); // if(oreDic == null || !OreDictionary.getOres(oreDic).isEmpty()) // validRecipes.add(recipe); // } // return validRecipes; // } // }
import brightspark.sparkshammers.hammerCrafting.HammerCraftingManager; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.InventoryCrafting; import net.minecraft.inventory.SlotCrafting; import net.minecraft.item.ItemStack; import net.minecraft.util.NonNullList;
package brightspark.sparkshammers.gui; public class SlotSHCrafting extends SlotCrafting { private InventoryCrafting craftMatrix; public SlotSHCrafting(EntityPlayer player, InventoryCrafting craftingInventory, IInventory inventoryIn, int slotIndex, int xPosition, int yPosition) { super(player, craftingInventory, inventoryIn, slotIndex, xPosition, yPosition); this.craftMatrix = craftingInventory; } /** * Similar to the SlotCrafting implementation, but using HammerCraftingManager.getRemainingItems */ @Override public ItemStack onTake(EntityPlayer player, ItemStack stack) { onCrafting(stack);
// Path: src/main/java/brightspark/sparkshammers/hammerCrafting/HammerCraftingManager.java // public class HammerCraftingManager // { // public static IForgeRegistry<HammerShapedOreRecipe> REGISTRY; // // /** // * Returns the static instance of this class // */ // public static void setRegistry(IForgeRegistry<HammerShapedOreRecipe> registry) // { // REGISTRY = registry; // } // // public static List<HammerShapedOreRecipe> getRecipes() // { // return REGISTRY.getValues(); // } // // private HammerCraftingManager() {} // // public static ItemStack findMatchingRecipe(InventoryCrafting invCrafting) // { // for(HammerShapedOreRecipe recipe : REGISTRY) // if(recipe.matches(invCrafting)) // return recipe.getRecipeOutput(); // // return ItemStack.EMPTY; // } // // public static NonNullList<ItemStack> getRemainingItems(InventoryCrafting inv) // { // for (HammerShapedOreRecipe recipe : REGISTRY) // if (recipe.matches(inv)) // return recipe.getRemainingItems(inv); // return ForgeHooks.defaultRecipeGetRemainingItems(inv); // } // // /** // * Returns the list of all valid recipes which do not have any missing ingredients // * This is used by the JEI plugin // */ // public static List<HammerShapedOreRecipe> getValidRecipeList() // { // List<HammerShapedOreRecipe> validRecipes = Lists.newArrayList(); // for(HammerShapedOreRecipe recipe : REGISTRY) // { // String oreDic = ((ItemAOE) recipe.getRecipeOutput().getItem()).getDependantOreDic(); // if(oreDic == null || !OreDictionary.getOres(oreDic).isEmpty()) // validRecipes.add(recipe); // } // return validRecipes; // } // } // Path: src/main/java/brightspark/sparkshammers/gui/SlotSHCrafting.java import brightspark.sparkshammers.hammerCrafting.HammerCraftingManager; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.InventoryCrafting; import net.minecraft.inventory.SlotCrafting; import net.minecraft.item.ItemStack; import net.minecraft.util.NonNullList; package brightspark.sparkshammers.gui; public class SlotSHCrafting extends SlotCrafting { private InventoryCrafting craftMatrix; public SlotSHCrafting(EntityPlayer player, InventoryCrafting craftingInventory, IInventory inventoryIn, int slotIndex, int xPosition, int yPosition) { super(player, craftingInventory, inventoryIn, slotIndex, xPosition, yPosition); this.craftMatrix = craftingInventory; } /** * Similar to the SlotCrafting implementation, but using HammerCraftingManager.getRemainingItems */ @Override public ItemStack onTake(EntityPlayer player, ItemStack stack) { onCrafting(stack);
NonNullList<ItemStack> remaining = HammerCraftingManager.getRemainingItems(craftMatrix);
thebrightspark/SparksHammers
src/main/java/brightspark/sparkshammers/item/ItemUpgrade.java
// Path: src/main/java/brightspark/sparkshammers/item/upgrade/EnumUpgrades.java // public enum EnumUpgrades // { // SIZE(2), // SPEED(3), // ATTACK(3), // HARVEST, // CAPACITY(4); // // private short maxUpgrades = 1; // // EnumUpgrades() {} // // EnumUpgrades(int maxUpgrades) // { // this.maxUpgrades = (short) maxUpgrades; // } // // public short getMaxUpgrades() // { // return maxUpgrades; // } // // @Override // public String toString() // { // return name().toLowerCase(); // } // // @SideOnly(Side.CLIENT) // public String toLocal() // { // return I18n.format("upgrade." + toString() + ".name"); // } // }
import brightspark.sparkshammers.item.upgrade.EnumUpgrades;
package brightspark.sparkshammers.item; public class ItemUpgrade extends ItemResource {
// Path: src/main/java/brightspark/sparkshammers/item/upgrade/EnumUpgrades.java // public enum EnumUpgrades // { // SIZE(2), // SPEED(3), // ATTACK(3), // HARVEST, // CAPACITY(4); // // private short maxUpgrades = 1; // // EnumUpgrades() {} // // EnumUpgrades(int maxUpgrades) // { // this.maxUpgrades = (short) maxUpgrades; // } // // public short getMaxUpgrades() // { // return maxUpgrades; // } // // @Override // public String toString() // { // return name().toLowerCase(); // } // // @SideOnly(Side.CLIENT) // public String toLocal() // { // return I18n.format("upgrade." + toString() + ".name"); // } // } // Path: src/main/java/brightspark/sparkshammers/item/ItemUpgrade.java import brightspark.sparkshammers.item.upgrade.EnumUpgrades; package brightspark.sparkshammers.item; public class ItemUpgrade extends ItemResource {
private EnumUpgrades upgrade;
thebrightspark/SparksHammers
src/main/java/brightspark/sparkshammers/gui/GuiHandler.java
// Path: src/main/java/brightspark/sparkshammers/init/SHBlocks.java // public class SHBlocks // { // public static List<Block> BLOCKS; // public static List<ItemBlock> ITEM_BLOCKS; // // public static BlockHammer blockHammer = new BlockHammer(); // public static BlockHammerCraft blockHammerCraft = new BlockHammerCraft(); // // public static void addBlock(Block block) // { // BLOCKS.add(block); // ITEM_BLOCKS.add((ItemBlock) new ItemBlock(block).setRegistryName(block.getRegistryName())); // } // // private static void init() // { // BLOCKS = new ArrayList<>(); // ITEM_BLOCKS = new ArrayList<>(); // // addBlock(blockHammer); // addBlock(blockHammerCraft); // } // // public static Block[] getBlocks() // { // if(BLOCKS == null) init(); // return BLOCKS.toArray(new Block[0]); // } // // public static ItemBlock[] getItemBlocks() // { // if(ITEM_BLOCKS == null) init(); // return ITEM_BLOCKS.toArray(new ItemBlock[0]); // } // }
import brightspark.sparkshammers.init.SHBlocks; import net.minecraft.block.Block; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraftforge.fml.common.network.IGuiHandler;
package brightspark.sparkshammers.gui; public class GuiHandler implements IGuiHandler { @Override public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) { Block block = world.getBlockState(new BlockPos(x, y, z)).getBlock(); //Server side - returns instance of the container
// Path: src/main/java/brightspark/sparkshammers/init/SHBlocks.java // public class SHBlocks // { // public static List<Block> BLOCKS; // public static List<ItemBlock> ITEM_BLOCKS; // // public static BlockHammer blockHammer = new BlockHammer(); // public static BlockHammerCraft blockHammerCraft = new BlockHammerCraft(); // // public static void addBlock(Block block) // { // BLOCKS.add(block); // ITEM_BLOCKS.add((ItemBlock) new ItemBlock(block).setRegistryName(block.getRegistryName())); // } // // private static void init() // { // BLOCKS = new ArrayList<>(); // ITEM_BLOCKS = new ArrayList<>(); // // addBlock(blockHammer); // addBlock(blockHammerCraft); // } // // public static Block[] getBlocks() // { // if(BLOCKS == null) init(); // return BLOCKS.toArray(new Block[0]); // } // // public static ItemBlock[] getItemBlocks() // { // if(ITEM_BLOCKS == null) init(); // return ITEM_BLOCKS.toArray(new ItemBlock[0]); // } // } // Path: src/main/java/brightspark/sparkshammers/gui/GuiHandler.java import brightspark.sparkshammers.init.SHBlocks; import net.minecraft.block.Block; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraftforge.fml.common.network.IGuiHandler; package brightspark.sparkshammers.gui; public class GuiHandler implements IGuiHandler { @Override public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) { Block block = world.getBlockState(new BlockPos(x, y, z)).getBlock(); //Server side - returns instance of the container
if(block == SHBlocks.blockHammerCraft)
thebrightspark/SparksHammers
src/main/java/brightspark/sparkshammers/gui/GuiHammerCraft.java
// Path: src/main/java/brightspark/sparkshammers/init/SHBlocks.java // public class SHBlocks // { // public static List<Block> BLOCKS; // public static List<ItemBlock> ITEM_BLOCKS; // // public static BlockHammer blockHammer = new BlockHammer(); // public static BlockHammerCraft blockHammerCraft = new BlockHammerCraft(); // // public static void addBlock(Block block) // { // BLOCKS.add(block); // ITEM_BLOCKS.add((ItemBlock) new ItemBlock(block).setRegistryName(block.getRegistryName())); // } // // private static void init() // { // BLOCKS = new ArrayList<>(); // ITEM_BLOCKS = new ArrayList<>(); // // addBlock(blockHammer); // addBlock(blockHammerCraft); // } // // public static Block[] getBlocks() // { // if(BLOCKS == null) init(); // return BLOCKS.toArray(new Block[0]); // } // // public static ItemBlock[] getItemBlocks() // { // if(ITEM_BLOCKS == null) init(); // return ITEM_BLOCKS.toArray(new ItemBlock[0]); // } // }
import brightspark.sparkshammers.init.SHBlocks; import net.minecraft.client.resources.I18n; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.world.World;
package brightspark.sparkshammers.gui; public class GuiHammerCraft extends GuiContainerBase<ContainerHammerCraft> { public GuiHammerCraft(InventoryPlayer invPlayer, World world, int x, int y, int z) { super(new ContainerHammerCraft(invPlayer, world, x, y, z), "gui_hammer_craft"); xSize = 184; ySize = 219; } @Override protected void drawGuiContainerForegroundLayer(int p_146979_1_, int p_146979_2_) { //Draw text
// Path: src/main/java/brightspark/sparkshammers/init/SHBlocks.java // public class SHBlocks // { // public static List<Block> BLOCKS; // public static List<ItemBlock> ITEM_BLOCKS; // // public static BlockHammer blockHammer = new BlockHammer(); // public static BlockHammerCraft blockHammerCraft = new BlockHammerCraft(); // // public static void addBlock(Block block) // { // BLOCKS.add(block); // ITEM_BLOCKS.add((ItemBlock) new ItemBlock(block).setRegistryName(block.getRegistryName())); // } // // private static void init() // { // BLOCKS = new ArrayList<>(); // ITEM_BLOCKS = new ArrayList<>(); // // addBlock(blockHammer); // addBlock(blockHammerCraft); // } // // public static Block[] getBlocks() // { // if(BLOCKS == null) init(); // return BLOCKS.toArray(new Block[0]); // } // // public static ItemBlock[] getItemBlocks() // { // if(ITEM_BLOCKS == null) init(); // return ITEM_BLOCKS.toArray(new ItemBlock[0]); // } // } // Path: src/main/java/brightspark/sparkshammers/gui/GuiHammerCraft.java import brightspark.sparkshammers.init.SHBlocks; import net.minecraft.client.resources.I18n; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.world.World; package brightspark.sparkshammers.gui; public class GuiHammerCraft extends GuiContainerBase<ContainerHammerCraft> { public GuiHammerCraft(InventoryPlayer invPlayer, World world, int x, int y, int z) { super(new ContainerHammerCraft(invPlayer, world, x, y, z), "gui_hammer_craft"); xSize = 184; ySize = 219; } @Override protected void drawGuiContainerForegroundLayer(int p_146979_1_, int p_146979_2_) { //Draw text
fontRenderer.drawString(I18n.format(SHBlocks.blockHammerCraft.getUnlocalizedName() + ".name"), 12, 6, 4210752);
thebrightspark/SparksHammers
src/main/java/brightspark/sparkshammers/integration/jei/HammerCraftingTable/HammerCraftingRecipeWrapper.java
// Path: src/main/java/brightspark/sparkshammers/hammerCrafting/HammerShapedOreRecipe.java // public class HammerShapedOreRecipe extends IForgeRegistryEntry.Impl<HammerShapedOreRecipe> // { // //Added in for future ease of change, but hard coded for now. // private static final int MAX_CRAFT_GRID_WIDTH = 5; // private static final int MAX_CRAFT_GRID_HEIGHT = 3; // // private ItemStack output = ItemStack.EMPTY; // private NonNullList<Ingredient> input = NonNullList.create(); // public int width = 0; // public int height = 0; // // public HammerShapedOreRecipe(Block result, Object... recipe){ this(new ItemStack(result), recipe); } // public HammerShapedOreRecipe(Item result, Object... recipe){ this(new ItemStack(result), recipe); } // public HammerShapedOreRecipe(ItemStack result, Object... recipe) // { // output = result.copy(); // CraftingHelper.ShapedPrimer primer = CraftingHelper.parseShaped(recipe); // width = primer.width; // height = primer.height; // input = primer.input; // setRegistryName(result.getItem().getRegistryName()); // } // // public ItemStack getRecipeOutput(){ return output.copy(); } // // public NonNullList<ItemStack> getRemainingItems(InventoryCrafting inv) // { // return ForgeHooks.defaultRecipeGetRemainingItems(inv); // } // // /** // * Used to check if a recipe matches current crafting inventory // */ // public boolean matches(InventoryCrafting inv) // { // for (int y = 0; y < MAX_CRAFT_GRID_HEIGHT; y++) // { // for (int x = 0; x < MAX_CRAFT_GRID_WIDTH; x++) // { // Ingredient target = input.get(x + (y * MAX_CRAFT_GRID_WIDTH)); // ItemStack slot = inv.getStackInRowAndColumn(x, y); // // if(!target.apply(slot)) // return false; // } // } // return true; // } // // @Override // public String toString() // { // StringBuilder str = new StringBuilder("Output: " + output.getUnlocalizedName() + ", Inputs: "); // for(Object o : input) // { // if(o instanceof ItemStack) // str.append(((ItemStack)o).getUnlocalizedName()); // else if(o instanceof Item) // str.append(((Item)o).getUnlocalizedName()); // else if(o instanceof Block) // str.append(((Block)o).getUnlocalizedName()); // else if(o instanceof String) // str.append((String)o); // else if(o instanceof List) // str.append("List of ").append(((List)o).size()); // else // str.append("<UNKNOWN>"); // str.append(", "); // } // return str.toString().substring(0, str.length()-2); // } // // /** // * Gets the inputs // */ // public NonNullList<Ingredient> getIngredients() // { // return input; // } // } // // Path: src/main/java/brightspark/sparkshammers/integration/jei/SparksHammersPlugin.java // @JEIPlugin // public class SparksHammersPlugin implements IModPlugin // { // public static IJeiHelpers jeiHelper; // // @Override // public void registerCategories(@Nonnull IRecipeCategoryRegistration registry) // { // jeiHelper = registry.getJeiHelpers(); // // registry.addRecipeCategories(new HammerCraftingRecipeCategory(jeiHelper.getGuiHelper())); // } // // @Override // public void register(@Nonnull IModRegistry registry) // { // registry.handleRecipes(HammerShapedOreRecipe.class, HammerCraftingRecipeWrapper.FACTORY, Reference.JEI.HAMMER_CRAFTING_UID); // registry.addRecipes(HammerCraftingManager.getValidRecipeList(), Reference.JEI.HAMMER_CRAFTING_UID); // registry.addRecipeClickArea(GuiHammerCraft.class, 111, 69, 26, 19, Reference.JEI.HAMMER_CRAFTING_UID); // registry.addRecipeCatalyst(new ItemStack(SHBlocks.blockHammerCraft), Reference.JEI.HAMMER_CRAFTING_UID); // // //Hide tools from JEI if you can't make them! // IIngredientBlacklist blacklist = jeiHelper.getIngredientBlacklist(); // int count = 0; // for(ItemAOE tool : SHItems.AOE_TOOLS) // { // if(SparksHammers.shouldHideTool(tool)) // { // blacklist.addIngredientToBlacklist(new ItemStack(tool)); // count++; // } // } // if(count > 0) // LogHelper.info("Hidden " + count + " tools from JEI due to missing ingredients"); // } // }
import brightspark.sparkshammers.hammerCrafting.HammerShapedOreRecipe; import brightspark.sparkshammers.integration.jei.SparksHammersPlugin; import mezz.jei.api.ingredients.IIngredients; import mezz.jei.api.recipe.IRecipeWrapper; import mezz.jei.api.recipe.IRecipeWrapperFactory; import net.minecraft.item.ItemStack; import java.util.List;
package brightspark.sparkshammers.integration.jei.HammerCraftingTable; public class HammerCraftingRecipeWrapper implements IRecipeWrapper { public static final Factory FACTORY = new Factory(); private List<List<ItemStack>> input; private ItemStack output;
// Path: src/main/java/brightspark/sparkshammers/hammerCrafting/HammerShapedOreRecipe.java // public class HammerShapedOreRecipe extends IForgeRegistryEntry.Impl<HammerShapedOreRecipe> // { // //Added in for future ease of change, but hard coded for now. // private static final int MAX_CRAFT_GRID_WIDTH = 5; // private static final int MAX_CRAFT_GRID_HEIGHT = 3; // // private ItemStack output = ItemStack.EMPTY; // private NonNullList<Ingredient> input = NonNullList.create(); // public int width = 0; // public int height = 0; // // public HammerShapedOreRecipe(Block result, Object... recipe){ this(new ItemStack(result), recipe); } // public HammerShapedOreRecipe(Item result, Object... recipe){ this(new ItemStack(result), recipe); } // public HammerShapedOreRecipe(ItemStack result, Object... recipe) // { // output = result.copy(); // CraftingHelper.ShapedPrimer primer = CraftingHelper.parseShaped(recipe); // width = primer.width; // height = primer.height; // input = primer.input; // setRegistryName(result.getItem().getRegistryName()); // } // // public ItemStack getRecipeOutput(){ return output.copy(); } // // public NonNullList<ItemStack> getRemainingItems(InventoryCrafting inv) // { // return ForgeHooks.defaultRecipeGetRemainingItems(inv); // } // // /** // * Used to check if a recipe matches current crafting inventory // */ // public boolean matches(InventoryCrafting inv) // { // for (int y = 0; y < MAX_CRAFT_GRID_HEIGHT; y++) // { // for (int x = 0; x < MAX_CRAFT_GRID_WIDTH; x++) // { // Ingredient target = input.get(x + (y * MAX_CRAFT_GRID_WIDTH)); // ItemStack slot = inv.getStackInRowAndColumn(x, y); // // if(!target.apply(slot)) // return false; // } // } // return true; // } // // @Override // public String toString() // { // StringBuilder str = new StringBuilder("Output: " + output.getUnlocalizedName() + ", Inputs: "); // for(Object o : input) // { // if(o instanceof ItemStack) // str.append(((ItemStack)o).getUnlocalizedName()); // else if(o instanceof Item) // str.append(((Item)o).getUnlocalizedName()); // else if(o instanceof Block) // str.append(((Block)o).getUnlocalizedName()); // else if(o instanceof String) // str.append((String)o); // else if(o instanceof List) // str.append("List of ").append(((List)o).size()); // else // str.append("<UNKNOWN>"); // str.append(", "); // } // return str.toString().substring(0, str.length()-2); // } // // /** // * Gets the inputs // */ // public NonNullList<Ingredient> getIngredients() // { // return input; // } // } // // Path: src/main/java/brightspark/sparkshammers/integration/jei/SparksHammersPlugin.java // @JEIPlugin // public class SparksHammersPlugin implements IModPlugin // { // public static IJeiHelpers jeiHelper; // // @Override // public void registerCategories(@Nonnull IRecipeCategoryRegistration registry) // { // jeiHelper = registry.getJeiHelpers(); // // registry.addRecipeCategories(new HammerCraftingRecipeCategory(jeiHelper.getGuiHelper())); // } // // @Override // public void register(@Nonnull IModRegistry registry) // { // registry.handleRecipes(HammerShapedOreRecipe.class, HammerCraftingRecipeWrapper.FACTORY, Reference.JEI.HAMMER_CRAFTING_UID); // registry.addRecipes(HammerCraftingManager.getValidRecipeList(), Reference.JEI.HAMMER_CRAFTING_UID); // registry.addRecipeClickArea(GuiHammerCraft.class, 111, 69, 26, 19, Reference.JEI.HAMMER_CRAFTING_UID); // registry.addRecipeCatalyst(new ItemStack(SHBlocks.blockHammerCraft), Reference.JEI.HAMMER_CRAFTING_UID); // // //Hide tools from JEI if you can't make them! // IIngredientBlacklist blacklist = jeiHelper.getIngredientBlacklist(); // int count = 0; // for(ItemAOE tool : SHItems.AOE_TOOLS) // { // if(SparksHammers.shouldHideTool(tool)) // { // blacklist.addIngredientToBlacklist(new ItemStack(tool)); // count++; // } // } // if(count > 0) // LogHelper.info("Hidden " + count + " tools from JEI due to missing ingredients"); // } // } // Path: src/main/java/brightspark/sparkshammers/integration/jei/HammerCraftingTable/HammerCraftingRecipeWrapper.java import brightspark.sparkshammers.hammerCrafting.HammerShapedOreRecipe; import brightspark.sparkshammers.integration.jei.SparksHammersPlugin; import mezz.jei.api.ingredients.IIngredients; import mezz.jei.api.recipe.IRecipeWrapper; import mezz.jei.api.recipe.IRecipeWrapperFactory; import net.minecraft.item.ItemStack; import java.util.List; package brightspark.sparkshammers.integration.jei.HammerCraftingTable; public class HammerCraftingRecipeWrapper implements IRecipeWrapper { public static final Factory FACTORY = new Factory(); private List<List<ItemStack>> input; private ItemStack output;
public HammerCraftingRecipeWrapper(HammerShapedOreRecipe recipe)
thebrightspark/SparksHammers
src/main/java/brightspark/sparkshammers/integration/jei/HammerCraftingTable/HammerCraftingRecipeWrapper.java
// Path: src/main/java/brightspark/sparkshammers/hammerCrafting/HammerShapedOreRecipe.java // public class HammerShapedOreRecipe extends IForgeRegistryEntry.Impl<HammerShapedOreRecipe> // { // //Added in for future ease of change, but hard coded for now. // private static final int MAX_CRAFT_GRID_WIDTH = 5; // private static final int MAX_CRAFT_GRID_HEIGHT = 3; // // private ItemStack output = ItemStack.EMPTY; // private NonNullList<Ingredient> input = NonNullList.create(); // public int width = 0; // public int height = 0; // // public HammerShapedOreRecipe(Block result, Object... recipe){ this(new ItemStack(result), recipe); } // public HammerShapedOreRecipe(Item result, Object... recipe){ this(new ItemStack(result), recipe); } // public HammerShapedOreRecipe(ItemStack result, Object... recipe) // { // output = result.copy(); // CraftingHelper.ShapedPrimer primer = CraftingHelper.parseShaped(recipe); // width = primer.width; // height = primer.height; // input = primer.input; // setRegistryName(result.getItem().getRegistryName()); // } // // public ItemStack getRecipeOutput(){ return output.copy(); } // // public NonNullList<ItemStack> getRemainingItems(InventoryCrafting inv) // { // return ForgeHooks.defaultRecipeGetRemainingItems(inv); // } // // /** // * Used to check if a recipe matches current crafting inventory // */ // public boolean matches(InventoryCrafting inv) // { // for (int y = 0; y < MAX_CRAFT_GRID_HEIGHT; y++) // { // for (int x = 0; x < MAX_CRAFT_GRID_WIDTH; x++) // { // Ingredient target = input.get(x + (y * MAX_CRAFT_GRID_WIDTH)); // ItemStack slot = inv.getStackInRowAndColumn(x, y); // // if(!target.apply(slot)) // return false; // } // } // return true; // } // // @Override // public String toString() // { // StringBuilder str = new StringBuilder("Output: " + output.getUnlocalizedName() + ", Inputs: "); // for(Object o : input) // { // if(o instanceof ItemStack) // str.append(((ItemStack)o).getUnlocalizedName()); // else if(o instanceof Item) // str.append(((Item)o).getUnlocalizedName()); // else if(o instanceof Block) // str.append(((Block)o).getUnlocalizedName()); // else if(o instanceof String) // str.append((String)o); // else if(o instanceof List) // str.append("List of ").append(((List)o).size()); // else // str.append("<UNKNOWN>"); // str.append(", "); // } // return str.toString().substring(0, str.length()-2); // } // // /** // * Gets the inputs // */ // public NonNullList<Ingredient> getIngredients() // { // return input; // } // } // // Path: src/main/java/brightspark/sparkshammers/integration/jei/SparksHammersPlugin.java // @JEIPlugin // public class SparksHammersPlugin implements IModPlugin // { // public static IJeiHelpers jeiHelper; // // @Override // public void registerCategories(@Nonnull IRecipeCategoryRegistration registry) // { // jeiHelper = registry.getJeiHelpers(); // // registry.addRecipeCategories(new HammerCraftingRecipeCategory(jeiHelper.getGuiHelper())); // } // // @Override // public void register(@Nonnull IModRegistry registry) // { // registry.handleRecipes(HammerShapedOreRecipe.class, HammerCraftingRecipeWrapper.FACTORY, Reference.JEI.HAMMER_CRAFTING_UID); // registry.addRecipes(HammerCraftingManager.getValidRecipeList(), Reference.JEI.HAMMER_CRAFTING_UID); // registry.addRecipeClickArea(GuiHammerCraft.class, 111, 69, 26, 19, Reference.JEI.HAMMER_CRAFTING_UID); // registry.addRecipeCatalyst(new ItemStack(SHBlocks.blockHammerCraft), Reference.JEI.HAMMER_CRAFTING_UID); // // //Hide tools from JEI if you can't make them! // IIngredientBlacklist blacklist = jeiHelper.getIngredientBlacklist(); // int count = 0; // for(ItemAOE tool : SHItems.AOE_TOOLS) // { // if(SparksHammers.shouldHideTool(tool)) // { // blacklist.addIngredientToBlacklist(new ItemStack(tool)); // count++; // } // } // if(count > 0) // LogHelper.info("Hidden " + count + " tools from JEI due to missing ingredients"); // } // }
import brightspark.sparkshammers.hammerCrafting.HammerShapedOreRecipe; import brightspark.sparkshammers.integration.jei.SparksHammersPlugin; import mezz.jei.api.ingredients.IIngredients; import mezz.jei.api.recipe.IRecipeWrapper; import mezz.jei.api.recipe.IRecipeWrapperFactory; import net.minecraft.item.ItemStack; import java.util.List;
package brightspark.sparkshammers.integration.jei.HammerCraftingTable; public class HammerCraftingRecipeWrapper implements IRecipeWrapper { public static final Factory FACTORY = new Factory(); private List<List<ItemStack>> input; private ItemStack output; public HammerCraftingRecipeWrapper(HammerShapedOreRecipe recipe) {
// Path: src/main/java/brightspark/sparkshammers/hammerCrafting/HammerShapedOreRecipe.java // public class HammerShapedOreRecipe extends IForgeRegistryEntry.Impl<HammerShapedOreRecipe> // { // //Added in for future ease of change, but hard coded for now. // private static final int MAX_CRAFT_GRID_WIDTH = 5; // private static final int MAX_CRAFT_GRID_HEIGHT = 3; // // private ItemStack output = ItemStack.EMPTY; // private NonNullList<Ingredient> input = NonNullList.create(); // public int width = 0; // public int height = 0; // // public HammerShapedOreRecipe(Block result, Object... recipe){ this(new ItemStack(result), recipe); } // public HammerShapedOreRecipe(Item result, Object... recipe){ this(new ItemStack(result), recipe); } // public HammerShapedOreRecipe(ItemStack result, Object... recipe) // { // output = result.copy(); // CraftingHelper.ShapedPrimer primer = CraftingHelper.parseShaped(recipe); // width = primer.width; // height = primer.height; // input = primer.input; // setRegistryName(result.getItem().getRegistryName()); // } // // public ItemStack getRecipeOutput(){ return output.copy(); } // // public NonNullList<ItemStack> getRemainingItems(InventoryCrafting inv) // { // return ForgeHooks.defaultRecipeGetRemainingItems(inv); // } // // /** // * Used to check if a recipe matches current crafting inventory // */ // public boolean matches(InventoryCrafting inv) // { // for (int y = 0; y < MAX_CRAFT_GRID_HEIGHT; y++) // { // for (int x = 0; x < MAX_CRAFT_GRID_WIDTH; x++) // { // Ingredient target = input.get(x + (y * MAX_CRAFT_GRID_WIDTH)); // ItemStack slot = inv.getStackInRowAndColumn(x, y); // // if(!target.apply(slot)) // return false; // } // } // return true; // } // // @Override // public String toString() // { // StringBuilder str = new StringBuilder("Output: " + output.getUnlocalizedName() + ", Inputs: "); // for(Object o : input) // { // if(o instanceof ItemStack) // str.append(((ItemStack)o).getUnlocalizedName()); // else if(o instanceof Item) // str.append(((Item)o).getUnlocalizedName()); // else if(o instanceof Block) // str.append(((Block)o).getUnlocalizedName()); // else if(o instanceof String) // str.append((String)o); // else if(o instanceof List) // str.append("List of ").append(((List)o).size()); // else // str.append("<UNKNOWN>"); // str.append(", "); // } // return str.toString().substring(0, str.length()-2); // } // // /** // * Gets the inputs // */ // public NonNullList<Ingredient> getIngredients() // { // return input; // } // } // // Path: src/main/java/brightspark/sparkshammers/integration/jei/SparksHammersPlugin.java // @JEIPlugin // public class SparksHammersPlugin implements IModPlugin // { // public static IJeiHelpers jeiHelper; // // @Override // public void registerCategories(@Nonnull IRecipeCategoryRegistration registry) // { // jeiHelper = registry.getJeiHelpers(); // // registry.addRecipeCategories(new HammerCraftingRecipeCategory(jeiHelper.getGuiHelper())); // } // // @Override // public void register(@Nonnull IModRegistry registry) // { // registry.handleRecipes(HammerShapedOreRecipe.class, HammerCraftingRecipeWrapper.FACTORY, Reference.JEI.HAMMER_CRAFTING_UID); // registry.addRecipes(HammerCraftingManager.getValidRecipeList(), Reference.JEI.HAMMER_CRAFTING_UID); // registry.addRecipeClickArea(GuiHammerCraft.class, 111, 69, 26, 19, Reference.JEI.HAMMER_CRAFTING_UID); // registry.addRecipeCatalyst(new ItemStack(SHBlocks.blockHammerCraft), Reference.JEI.HAMMER_CRAFTING_UID); // // //Hide tools from JEI if you can't make them! // IIngredientBlacklist blacklist = jeiHelper.getIngredientBlacklist(); // int count = 0; // for(ItemAOE tool : SHItems.AOE_TOOLS) // { // if(SparksHammers.shouldHideTool(tool)) // { // blacklist.addIngredientToBlacklist(new ItemStack(tool)); // count++; // } // } // if(count > 0) // LogHelper.info("Hidden " + count + " tools from JEI due to missing ingredients"); // } // } // Path: src/main/java/brightspark/sparkshammers/integration/jei/HammerCraftingTable/HammerCraftingRecipeWrapper.java import brightspark.sparkshammers.hammerCrafting.HammerShapedOreRecipe; import brightspark.sparkshammers.integration.jei.SparksHammersPlugin; import mezz.jei.api.ingredients.IIngredients; import mezz.jei.api.recipe.IRecipeWrapper; import mezz.jei.api.recipe.IRecipeWrapperFactory; import net.minecraft.item.ItemStack; import java.util.List; package brightspark.sparkshammers.integration.jei.HammerCraftingTable; public class HammerCraftingRecipeWrapper implements IRecipeWrapper { public static final Factory FACTORY = new Factory(); private List<List<ItemStack>> input; private ItemStack output; public HammerCraftingRecipeWrapper(HammerShapedOreRecipe recipe) {
input = SparksHammersPlugin.jeiHelper.getStackHelper().expandRecipeItemStackInputs(recipe.getIngredients());
thebrightspark/SparksHammers
src/main/java/brightspark/sparkshammers/item/ItemResource.java
// Path: src/main/java/brightspark/sparkshammers/SparksHammers.java // @Mod(modid=Reference.MOD_ID, name=Reference.MOD_NAME, version=Reference.VERSION, dependencies=Reference.DEPENDENCIES) // public class SparksHammers // { // //Instance of this mod that is safe to reference // @Mod.Instance(Reference.MOD_ID) // public static SparksHammers instance; // // public static final CreativeTabs SH_TAB = new CreativeTabs(Reference.MOD_ID) // { // @Override // public ItemStack getTabIconItem() // { // return new ItemStack(SHItems.hammerDiamond); // } // // @Override // public String getTranslatedTabLabel() // { // return Reference.MOD_NAME; // } // }; // // public static DamageSource fallingHammer = new DamageSource("fallingHammer"); // private static Advancement killDragonAdvancement; // // public static ItemStack TORCH_STACK; // public static ItemBlock TORCH_ITEM; // // private static Set SPECIAL_NAMES = Sets.newHashSet("mjolnir", "giant", "mini", "netherstar", "powered"); // // @Mod.EventHandler // public void init(FMLInitializationEvent event) // { // //Initialize GUIs, tile entities, recipies, event handlers here // // NetworkRegistry.INSTANCE.registerGuiHandler(this, new GuiHandler()); // // //Register world generation for Mjolnir Shrine // if(SHConfig.MJOLNIR.shouldGenerateMjolnirShrines) // GameRegistry.registerWorldGenerator(new WorldGenMjolnirShrine(), 10); // } // // @Mod.EventHandler // public void postInit(FMLPostInitializationEvent event) // { // //Run stuff after mods have initialized here // // TORCH_STACK = new ItemStack(Blocks.TORCH); // TORCH_ITEM = (ItemBlock) TORCH_STACK.getItem(); // // //Set the dependants for a tool to null if they have no recipe // int count = 0; // for(ItemAOE tool : SHItems.AOE_TOOLS) // { // if(shouldHideTool(tool)) // { // tool.nullDependants(); // count++; // } // } // if(count > 0) // LogHelper.info("Removed " + count + " tools from creative menu due to missing ingredients"); // // //Null all the lists so it's not taking up extra memory // SHItems.voidLists(); // SHBlocks.BLOCKS = null; // SHBlocks.ITEM_BLOCKS = null; // } // // public static boolean shouldHideTool(ItemAOE tool) // { // if(SPECIAL_NAMES.contains(tool.getMaterialName())) // return false; // ItemStack stack = tool.getDependantStack(); // String ore = tool.getDependantOreDic(); // return (stack == null || stack.isEmpty()) && (!OreDictionary.doesOreNameExist(ore) || OreDictionary.getOres(ore).isEmpty()); // } // // public static boolean hasKillDragonAdvancement(EntityPlayerMP player) // { // if(killDragonAdvancement == null) // killDragonAdvancement = player.getServer().getAdvancementManager().getAdvancement(new ResourceLocation("minecraft", "end/kill_dragon")); // return killDragonAdvancement != null && player.getAdvancements().getProgress(killDragonAdvancement).isDone(); // } // }
import brightspark.sparkshammers.SparksHammers; import net.minecraft.item.Item;
package brightspark.sparkshammers.item; public class ItemResource extends Item { public ItemResource(String name) { setUnlocalizedName(name); setMaxStackSize(64);
// Path: src/main/java/brightspark/sparkshammers/SparksHammers.java // @Mod(modid=Reference.MOD_ID, name=Reference.MOD_NAME, version=Reference.VERSION, dependencies=Reference.DEPENDENCIES) // public class SparksHammers // { // //Instance of this mod that is safe to reference // @Mod.Instance(Reference.MOD_ID) // public static SparksHammers instance; // // public static final CreativeTabs SH_TAB = new CreativeTabs(Reference.MOD_ID) // { // @Override // public ItemStack getTabIconItem() // { // return new ItemStack(SHItems.hammerDiamond); // } // // @Override // public String getTranslatedTabLabel() // { // return Reference.MOD_NAME; // } // }; // // public static DamageSource fallingHammer = new DamageSource("fallingHammer"); // private static Advancement killDragonAdvancement; // // public static ItemStack TORCH_STACK; // public static ItemBlock TORCH_ITEM; // // private static Set SPECIAL_NAMES = Sets.newHashSet("mjolnir", "giant", "mini", "netherstar", "powered"); // // @Mod.EventHandler // public void init(FMLInitializationEvent event) // { // //Initialize GUIs, tile entities, recipies, event handlers here // // NetworkRegistry.INSTANCE.registerGuiHandler(this, new GuiHandler()); // // //Register world generation for Mjolnir Shrine // if(SHConfig.MJOLNIR.shouldGenerateMjolnirShrines) // GameRegistry.registerWorldGenerator(new WorldGenMjolnirShrine(), 10); // } // // @Mod.EventHandler // public void postInit(FMLPostInitializationEvent event) // { // //Run stuff after mods have initialized here // // TORCH_STACK = new ItemStack(Blocks.TORCH); // TORCH_ITEM = (ItemBlock) TORCH_STACK.getItem(); // // //Set the dependants for a tool to null if they have no recipe // int count = 0; // for(ItemAOE tool : SHItems.AOE_TOOLS) // { // if(shouldHideTool(tool)) // { // tool.nullDependants(); // count++; // } // } // if(count > 0) // LogHelper.info("Removed " + count + " tools from creative menu due to missing ingredients"); // // //Null all the lists so it's not taking up extra memory // SHItems.voidLists(); // SHBlocks.BLOCKS = null; // SHBlocks.ITEM_BLOCKS = null; // } // // public static boolean shouldHideTool(ItemAOE tool) // { // if(SPECIAL_NAMES.contains(tool.getMaterialName())) // return false; // ItemStack stack = tool.getDependantStack(); // String ore = tool.getDependantOreDic(); // return (stack == null || stack.isEmpty()) && (!OreDictionary.doesOreNameExist(ore) || OreDictionary.getOres(ore).isEmpty()); // } // // public static boolean hasKillDragonAdvancement(EntityPlayerMP player) // { // if(killDragonAdvancement == null) // killDragonAdvancement = player.getServer().getAdvancementManager().getAdvancement(new ResourceLocation("minecraft", "end/kill_dragon")); // return killDragonAdvancement != null && player.getAdvancements().getProgress(killDragonAdvancement).isDone(); // } // } // Path: src/main/java/brightspark/sparkshammers/item/ItemResource.java import brightspark.sparkshammers.SparksHammers; import net.minecraft.item.Item; package brightspark.sparkshammers.item; public class ItemResource extends Item { public ItemResource(String name) { setUnlocalizedName(name); setMaxStackSize(64);
setCreativeTab(SparksHammers.SH_TAB);
thebrightspark/SparksHammers
src/main/java/brightspark/sparkshammers/api/RegisterToolEvent.java
// Path: src/main/java/brightspark/sparkshammers/customTools/Tool.java // public class Tool // { // public String name, localName; // public ToolMaterial material; // public int toolColour; // public String dependantOreDic; // public ItemStack dependantStack; // // protected Tool(String name, ToolMaterial material, int toolColour) // { // localName = name; // this.name = name.toLowerCase().replaceAll("\\s", ""); // this.material = material; // this.toolColour = toolColour; // } // // public Tool(String name, ToolMaterial material, int toolColour, Object dependantItem) // { // this(name, material, toolColour); // if(dependantItem == null) // return; // if(dependantItem instanceof String) // dependantOreDic = (String) dependantItem; // else if(dependantItem instanceof ItemStack) // dependantStack = (ItemStack) dependantItem; // else // throw new IllegalArgumentException("Dependant Item must be a String (ore dictionary) or an ItemStack!"); // } // // public Tool(EnumMaterials enumMaterial) // { // this(enumMaterial.getMaterialName(), enumMaterial.material, enumMaterial.colour); // if(enumMaterial.dependantOreDic != null) // dependantOreDic = enumMaterial.dependantOreDic; // } // // public String getToolName(boolean isExcavator) // { // return (isExcavator ? Reference.Items.EXCAVATOR : Reference.Items.HAMMER) + "_" + name; // } // }
import brightspark.sparkshammers.customTools.Tool; import net.minecraftforge.fml.common.eventhandler.Event; import java.util.Arrays; import java.util.List;
package brightspark.sparkshammers.api; /** * Fired right before items are registered for Sparks Hammers so that other mods can add their own tools to be * registered. */ public class RegisterToolEvent extends Event {
// Path: src/main/java/brightspark/sparkshammers/customTools/Tool.java // public class Tool // { // public String name, localName; // public ToolMaterial material; // public int toolColour; // public String dependantOreDic; // public ItemStack dependantStack; // // protected Tool(String name, ToolMaterial material, int toolColour) // { // localName = name; // this.name = name.toLowerCase().replaceAll("\\s", ""); // this.material = material; // this.toolColour = toolColour; // } // // public Tool(String name, ToolMaterial material, int toolColour, Object dependantItem) // { // this(name, material, toolColour); // if(dependantItem == null) // return; // if(dependantItem instanceof String) // dependantOreDic = (String) dependantItem; // else if(dependantItem instanceof ItemStack) // dependantStack = (ItemStack) dependantItem; // else // throw new IllegalArgumentException("Dependant Item must be a String (ore dictionary) or an ItemStack!"); // } // // public Tool(EnumMaterials enumMaterial) // { // this(enumMaterial.getMaterialName(), enumMaterial.material, enumMaterial.colour); // if(enumMaterial.dependantOreDic != null) // dependantOreDic = enumMaterial.dependantOreDic; // } // // public String getToolName(boolean isExcavator) // { // return (isExcavator ? Reference.Items.EXCAVATOR : Reference.Items.HAMMER) + "_" + name; // } // } // Path: src/main/java/brightspark/sparkshammers/api/RegisterToolEvent.java import brightspark.sparkshammers.customTools.Tool; import net.minecraftforge.fml.common.eventhandler.Event; import java.util.Arrays; import java.util.List; package brightspark.sparkshammers.api; /** * Fired right before items are registered for Sparks Hammers so that other mods can add their own tools to be * registered. */ public class RegisterToolEvent extends Event {
private final List<Tool> toolsList;
wuzhongdehua/fksm
storm/src/main/java/com/fksm/storm/bolt/ServerServiceWindowBolt.java
// Path: common/src/main/java/com/fksm/common/util/Constants.java // public class Constants { // /** The Constant REGEX. */ // public static final String REGEX_UUID = "regex.uuid"; // public static final String REGEX_IP = "regex.ip"; // public static final String REGEX_TIME = "regex.time"; // // public static final int TYPE_CALLER_INFO = 1; // public static final int TYPE_RESP_PARAM = 2; // public static final int TYPE_REQ_PARAM = 3; // public static final int TYPE_RESP_TIME = 4; // public static final int TYPE_SERVICE_INFO = 5; // // public static final String REDIS_SERVER_KEY = "SERVER"; // // public static final String REDIS_SERVER_SERVICE_PREFIX = "SERVER_SERVICE_"; // public static final String REDIS_SERVICE_REQUEST_PREFIX = "SERVICE_REQUEST_"; // public static final String REDIS_TIME_REQUESTS_PREFIX = "TIME_REQUESTS_"; // //server->service->requests // public static final String REDIS_SERVER_SERVICE_REQUEST_PREFIX = "SERVER_SERVICE_REQUEST_"; // // public static final String REDIS_SERVICE_COSTS_PREFIX = "SERVICE_COSTS_"; // public static final String REDIS_SERVICE_CALLERS_PREFIX = "SERVICE_CALLERS_"; // public static final String REDIS_SERVICE_CODES_PREFIX = "SERVICE_CODES_"; // // public static final String REDIS_SERVICE_REQUEST_CALLER_PREFIX = "SERVICE_REQUEST_CALLER_"; // public static final String REDIS_SERVER_SERVICE_COST_PREFIX = "SERVER_SERVICE_COST_"; // public static final String REDIS_SERVICE_REQUEST_CODE_PREFIX = "SERVICE_REQUEST_CODE_"; // // public static final String REDIS_SERVER_PREFIX = "S_SERVER_SERVICE_REQUEST_"; // public static final String REDIS_SERVER_COSTS_PREFIX = "S_SERVER_SERVICE_COSTS_"; // public static final String REDIS_SERVER_CALLER_PREFIX = "S_SERVER_SERVICE_CALLER_"; // public static final String REDIS_SERVER_CODE_PREFIX = "S_SERVER_SERVICE_CODE_"; // // public static final String REDIS_TIMELINE_KEY = "TIMELINE_KEY"; // // public static final Integer CODE_SUCESS = 100; // } // // Path: storm/src/main/java/com/fksm/utils/CuratorLockAcquire.java // public class CuratorLockAcquire { // private static final Logger LOGGER = LoggerFactory.getLogger(CuratorLockAcquire.class); // // private CuratorFramework client = null; // // public CuratorLockAcquire() {} // // public synchronized CuratorFramework getCuratorClient() { // if (client == null) { // try { // String zkHostPort = ConfigPropertieUtil.getInstance().getString("curator.lock.zk.connect"); // RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3); // client = CuratorFrameworkFactory.newClient(zkHostPort, retryPolicy); // client.start(); // } catch (Exception e) { // LOGGER.error("Get curatorClient error.", e); // } // } // // return client; // } // }
import com.alibaba.fastjson.JSONObject; import com.fksm.common.util.Constants; import com.fksm.utils.CuratorLockAcquire; import com.netflix.curator.framework.recipes.locks.InterProcessMutex; import org.apache.storm.task.OutputCollector; import org.apache.storm.task.TopologyContext; import org.apache.storm.topology.OutputFieldsDeclarer; import org.apache.storm.tuple.Fields; import org.apache.storm.tuple.Tuple; import org.apache.storm.tuple.Values; import org.apache.storm.windowing.TupleWindow; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*;
package com.fksm.storm.bolt; /** * Created by root on 16-4-23. */ public class ServerServiceWindowBolt extends BaseRedisWindowBolt { private static final Logger logger = LoggerFactory.getLogger(ServerServiceWindowBolt.class); private OutputCollector collector; //分布式锁
// Path: common/src/main/java/com/fksm/common/util/Constants.java // public class Constants { // /** The Constant REGEX. */ // public static final String REGEX_UUID = "regex.uuid"; // public static final String REGEX_IP = "regex.ip"; // public static final String REGEX_TIME = "regex.time"; // // public static final int TYPE_CALLER_INFO = 1; // public static final int TYPE_RESP_PARAM = 2; // public static final int TYPE_REQ_PARAM = 3; // public static final int TYPE_RESP_TIME = 4; // public static final int TYPE_SERVICE_INFO = 5; // // public static final String REDIS_SERVER_KEY = "SERVER"; // // public static final String REDIS_SERVER_SERVICE_PREFIX = "SERVER_SERVICE_"; // public static final String REDIS_SERVICE_REQUEST_PREFIX = "SERVICE_REQUEST_"; // public static final String REDIS_TIME_REQUESTS_PREFIX = "TIME_REQUESTS_"; // //server->service->requests // public static final String REDIS_SERVER_SERVICE_REQUEST_PREFIX = "SERVER_SERVICE_REQUEST_"; // // public static final String REDIS_SERVICE_COSTS_PREFIX = "SERVICE_COSTS_"; // public static final String REDIS_SERVICE_CALLERS_PREFIX = "SERVICE_CALLERS_"; // public static final String REDIS_SERVICE_CODES_PREFIX = "SERVICE_CODES_"; // // public static final String REDIS_SERVICE_REQUEST_CALLER_PREFIX = "SERVICE_REQUEST_CALLER_"; // public static final String REDIS_SERVER_SERVICE_COST_PREFIX = "SERVER_SERVICE_COST_"; // public static final String REDIS_SERVICE_REQUEST_CODE_PREFIX = "SERVICE_REQUEST_CODE_"; // // public static final String REDIS_SERVER_PREFIX = "S_SERVER_SERVICE_REQUEST_"; // public static final String REDIS_SERVER_COSTS_PREFIX = "S_SERVER_SERVICE_COSTS_"; // public static final String REDIS_SERVER_CALLER_PREFIX = "S_SERVER_SERVICE_CALLER_"; // public static final String REDIS_SERVER_CODE_PREFIX = "S_SERVER_SERVICE_CODE_"; // // public static final String REDIS_TIMELINE_KEY = "TIMELINE_KEY"; // // public static final Integer CODE_SUCESS = 100; // } // // Path: storm/src/main/java/com/fksm/utils/CuratorLockAcquire.java // public class CuratorLockAcquire { // private static final Logger LOGGER = LoggerFactory.getLogger(CuratorLockAcquire.class); // // private CuratorFramework client = null; // // public CuratorLockAcquire() {} // // public synchronized CuratorFramework getCuratorClient() { // if (client == null) { // try { // String zkHostPort = ConfigPropertieUtil.getInstance().getString("curator.lock.zk.connect"); // RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3); // client = CuratorFrameworkFactory.newClient(zkHostPort, retryPolicy); // client.start(); // } catch (Exception e) { // LOGGER.error("Get curatorClient error.", e); // } // } // // return client; // } // } // Path: storm/src/main/java/com/fksm/storm/bolt/ServerServiceWindowBolt.java import com.alibaba.fastjson.JSONObject; import com.fksm.common.util.Constants; import com.fksm.utils.CuratorLockAcquire; import com.netflix.curator.framework.recipes.locks.InterProcessMutex; import org.apache.storm.task.OutputCollector; import org.apache.storm.task.TopologyContext; import org.apache.storm.topology.OutputFieldsDeclarer; import org.apache.storm.tuple.Fields; import org.apache.storm.tuple.Tuple; import org.apache.storm.tuple.Values; import org.apache.storm.windowing.TupleWindow; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; package com.fksm.storm.bolt; /** * Created by root on 16-4-23. */ public class ServerServiceWindowBolt extends BaseRedisWindowBolt { private static final Logger logger = LoggerFactory.getLogger(ServerServiceWindowBolt.class); private OutputCollector collector; //分布式锁
private CuratorLockAcquire curatorLockAcquire;
wuzhongdehua/fksm
storm/src/main/java/com/fksm/storm/bolt/ServerServiceWindowBolt.java
// Path: common/src/main/java/com/fksm/common/util/Constants.java // public class Constants { // /** The Constant REGEX. */ // public static final String REGEX_UUID = "regex.uuid"; // public static final String REGEX_IP = "regex.ip"; // public static final String REGEX_TIME = "regex.time"; // // public static final int TYPE_CALLER_INFO = 1; // public static final int TYPE_RESP_PARAM = 2; // public static final int TYPE_REQ_PARAM = 3; // public static final int TYPE_RESP_TIME = 4; // public static final int TYPE_SERVICE_INFO = 5; // // public static final String REDIS_SERVER_KEY = "SERVER"; // // public static final String REDIS_SERVER_SERVICE_PREFIX = "SERVER_SERVICE_"; // public static final String REDIS_SERVICE_REQUEST_PREFIX = "SERVICE_REQUEST_"; // public static final String REDIS_TIME_REQUESTS_PREFIX = "TIME_REQUESTS_"; // //server->service->requests // public static final String REDIS_SERVER_SERVICE_REQUEST_PREFIX = "SERVER_SERVICE_REQUEST_"; // // public static final String REDIS_SERVICE_COSTS_PREFIX = "SERVICE_COSTS_"; // public static final String REDIS_SERVICE_CALLERS_PREFIX = "SERVICE_CALLERS_"; // public static final String REDIS_SERVICE_CODES_PREFIX = "SERVICE_CODES_"; // // public static final String REDIS_SERVICE_REQUEST_CALLER_PREFIX = "SERVICE_REQUEST_CALLER_"; // public static final String REDIS_SERVER_SERVICE_COST_PREFIX = "SERVER_SERVICE_COST_"; // public static final String REDIS_SERVICE_REQUEST_CODE_PREFIX = "SERVICE_REQUEST_CODE_"; // // public static final String REDIS_SERVER_PREFIX = "S_SERVER_SERVICE_REQUEST_"; // public static final String REDIS_SERVER_COSTS_PREFIX = "S_SERVER_SERVICE_COSTS_"; // public static final String REDIS_SERVER_CALLER_PREFIX = "S_SERVER_SERVICE_CALLER_"; // public static final String REDIS_SERVER_CODE_PREFIX = "S_SERVER_SERVICE_CODE_"; // // public static final String REDIS_TIMELINE_KEY = "TIMELINE_KEY"; // // public static final Integer CODE_SUCESS = 100; // } // // Path: storm/src/main/java/com/fksm/utils/CuratorLockAcquire.java // public class CuratorLockAcquire { // private static final Logger LOGGER = LoggerFactory.getLogger(CuratorLockAcquire.class); // // private CuratorFramework client = null; // // public CuratorLockAcquire() {} // // public synchronized CuratorFramework getCuratorClient() { // if (client == null) { // try { // String zkHostPort = ConfigPropertieUtil.getInstance().getString("curator.lock.zk.connect"); // RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3); // client = CuratorFrameworkFactory.newClient(zkHostPort, retryPolicy); // client.start(); // } catch (Exception e) { // LOGGER.error("Get curatorClient error.", e); // } // } // // return client; // } // }
import com.alibaba.fastjson.JSONObject; import com.fksm.common.util.Constants; import com.fksm.utils.CuratorLockAcquire; import com.netflix.curator.framework.recipes.locks.InterProcessMutex; import org.apache.storm.task.OutputCollector; import org.apache.storm.task.TopologyContext; import org.apache.storm.topology.OutputFieldsDeclarer; import org.apache.storm.tuple.Fields; import org.apache.storm.tuple.Tuple; import org.apache.storm.tuple.Values; import org.apache.storm.windowing.TupleWindow; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*;
@Override public void execute(TupleWindow inputWindow) { logger.debug("start deal ServerServiceWindowBolt ..."); String server_ip = ""; String service_id = ""; String server_service = ""; List<Long> time = new ArrayList<>(); //此段时间内的请求的id Set<String> requests = new HashSet<>(); //调用者调用次数 Map<String, Integer> caller_count = new HashMap<>(); //响应时间最大值 Long maxLong = 0L; //响应成功次数 Integer respCount = 0; for(Tuple tuple: inputWindow.get()) { //添加到时间 time.add(tuple.getLongByField("timestamp")); server_service = tuple.getStringByField("server_service"); String[] ss = server_service.split("_"); server_ip = ss[0]; service_id = ss[1]; logger.debug("get server_ip KafkaJsonAnalysis : {}", server_ip); logger.debug("get service_id KafkaJsonAnalysis : {}", service_id); int type = tuple.getIntegerByField("type"); logger.debug("get type from KafkaJsonAnalysis : {}", type); JSONObject data = (JSONObject)tuple.getValueByField("data"); requests.add(data.getString("request_id")); logger.debug("get data from KafkaJsonAnalysis : {}", data); switch (type){
// Path: common/src/main/java/com/fksm/common/util/Constants.java // public class Constants { // /** The Constant REGEX. */ // public static final String REGEX_UUID = "regex.uuid"; // public static final String REGEX_IP = "regex.ip"; // public static final String REGEX_TIME = "regex.time"; // // public static final int TYPE_CALLER_INFO = 1; // public static final int TYPE_RESP_PARAM = 2; // public static final int TYPE_REQ_PARAM = 3; // public static final int TYPE_RESP_TIME = 4; // public static final int TYPE_SERVICE_INFO = 5; // // public static final String REDIS_SERVER_KEY = "SERVER"; // // public static final String REDIS_SERVER_SERVICE_PREFIX = "SERVER_SERVICE_"; // public static final String REDIS_SERVICE_REQUEST_PREFIX = "SERVICE_REQUEST_"; // public static final String REDIS_TIME_REQUESTS_PREFIX = "TIME_REQUESTS_"; // //server->service->requests // public static final String REDIS_SERVER_SERVICE_REQUEST_PREFIX = "SERVER_SERVICE_REQUEST_"; // // public static final String REDIS_SERVICE_COSTS_PREFIX = "SERVICE_COSTS_"; // public static final String REDIS_SERVICE_CALLERS_PREFIX = "SERVICE_CALLERS_"; // public static final String REDIS_SERVICE_CODES_PREFIX = "SERVICE_CODES_"; // // public static final String REDIS_SERVICE_REQUEST_CALLER_PREFIX = "SERVICE_REQUEST_CALLER_"; // public static final String REDIS_SERVER_SERVICE_COST_PREFIX = "SERVER_SERVICE_COST_"; // public static final String REDIS_SERVICE_REQUEST_CODE_PREFIX = "SERVICE_REQUEST_CODE_"; // // public static final String REDIS_SERVER_PREFIX = "S_SERVER_SERVICE_REQUEST_"; // public static final String REDIS_SERVER_COSTS_PREFIX = "S_SERVER_SERVICE_COSTS_"; // public static final String REDIS_SERVER_CALLER_PREFIX = "S_SERVER_SERVICE_CALLER_"; // public static final String REDIS_SERVER_CODE_PREFIX = "S_SERVER_SERVICE_CODE_"; // // public static final String REDIS_TIMELINE_KEY = "TIMELINE_KEY"; // // public static final Integer CODE_SUCESS = 100; // } // // Path: storm/src/main/java/com/fksm/utils/CuratorLockAcquire.java // public class CuratorLockAcquire { // private static final Logger LOGGER = LoggerFactory.getLogger(CuratorLockAcquire.class); // // private CuratorFramework client = null; // // public CuratorLockAcquire() {} // // public synchronized CuratorFramework getCuratorClient() { // if (client == null) { // try { // String zkHostPort = ConfigPropertieUtil.getInstance().getString("curator.lock.zk.connect"); // RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3); // client = CuratorFrameworkFactory.newClient(zkHostPort, retryPolicy); // client.start(); // } catch (Exception e) { // LOGGER.error("Get curatorClient error.", e); // } // } // // return client; // } // } // Path: storm/src/main/java/com/fksm/storm/bolt/ServerServiceWindowBolt.java import com.alibaba.fastjson.JSONObject; import com.fksm.common.util.Constants; import com.fksm.utils.CuratorLockAcquire; import com.netflix.curator.framework.recipes.locks.InterProcessMutex; import org.apache.storm.task.OutputCollector; import org.apache.storm.task.TopologyContext; import org.apache.storm.topology.OutputFieldsDeclarer; import org.apache.storm.tuple.Fields; import org.apache.storm.tuple.Tuple; import org.apache.storm.tuple.Values; import org.apache.storm.windowing.TupleWindow; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; @Override public void execute(TupleWindow inputWindow) { logger.debug("start deal ServerServiceWindowBolt ..."); String server_ip = ""; String service_id = ""; String server_service = ""; List<Long> time = new ArrayList<>(); //此段时间内的请求的id Set<String> requests = new HashSet<>(); //调用者调用次数 Map<String, Integer> caller_count = new HashMap<>(); //响应时间最大值 Long maxLong = 0L; //响应成功次数 Integer respCount = 0; for(Tuple tuple: inputWindow.get()) { //添加到时间 time.add(tuple.getLongByField("timestamp")); server_service = tuple.getStringByField("server_service"); String[] ss = server_service.split("_"); server_ip = ss[0]; service_id = ss[1]; logger.debug("get server_ip KafkaJsonAnalysis : {}", server_ip); logger.debug("get service_id KafkaJsonAnalysis : {}", service_id); int type = tuple.getIntegerByField("type"); logger.debug("get type from KafkaJsonAnalysis : {}", type); JSONObject data = (JSONObject)tuple.getValueByField("data"); requests.add(data.getString("request_id")); logger.debug("get data from KafkaJsonAnalysis : {}", data); switch (type){
case Constants.TYPE_CALLER_INFO:
wuzhongdehua/fksm
storm/src/main/java/com/fksm/storm/bolt/RemoveRedisBolt.java
// Path: storm/src/main/java/com/fksm/utils/CuratorLockAcquire.java // public class CuratorLockAcquire { // private static final Logger LOGGER = LoggerFactory.getLogger(CuratorLockAcquire.class); // // private CuratorFramework client = null; // // public CuratorLockAcquire() {} // // public synchronized CuratorFramework getCuratorClient() { // if (client == null) { // try { // String zkHostPort = ConfigPropertieUtil.getInstance().getString("curator.lock.zk.connect"); // RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3); // client = CuratorFrameworkFactory.newClient(zkHostPort, retryPolicy); // client.start(); // } catch (Exception e) { // LOGGER.error("Get curatorClient error.", e); // } // } // // return client; // } // } // // Path: storm/src/main/java/com/fksm/utils/RedisKeysQueueManager.java // public class RedisKeysQueueManager { // private static ConcurrentLinkedQueue<String> queue = new ConcurrentLinkedQueue<String>(); // // public static void add(String key){ // queue.add(key); // } // // public static String pop(){ // if(!queue.isEmpty()) { // return queue.poll(); // } // return null; // } // // public static boolean isEmpty(){ // return queue.isEmpty(); // } // // public static int size(){ // return queue.size(); // } // }
import com.fksm.utils.CuratorLockAcquire; import com.fksm.utils.RedisKeysQueueManager; import com.netflix.curator.framework.recipes.locks.InterProcessMutex; import org.apache.storm.task.OutputCollector; import org.apache.storm.task.TopologyContext; import org.apache.storm.topology.OutputFieldsDeclarer; import org.apache.storm.tuple.Tuple; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*;
package com.fksm.storm.bolt; /** * remove data from redis */ public class RemoveRedisBolt extends BaseRedisBasicBolt { private static final Logger logger = LoggerFactory.getLogger(RemoveRedisBolt.class);
// Path: storm/src/main/java/com/fksm/utils/CuratorLockAcquire.java // public class CuratorLockAcquire { // private static final Logger LOGGER = LoggerFactory.getLogger(CuratorLockAcquire.class); // // private CuratorFramework client = null; // // public CuratorLockAcquire() {} // // public synchronized CuratorFramework getCuratorClient() { // if (client == null) { // try { // String zkHostPort = ConfigPropertieUtil.getInstance().getString("curator.lock.zk.connect"); // RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3); // client = CuratorFrameworkFactory.newClient(zkHostPort, retryPolicy); // client.start(); // } catch (Exception e) { // LOGGER.error("Get curatorClient error.", e); // } // } // // return client; // } // } // // Path: storm/src/main/java/com/fksm/utils/RedisKeysQueueManager.java // public class RedisKeysQueueManager { // private static ConcurrentLinkedQueue<String> queue = new ConcurrentLinkedQueue<String>(); // // public static void add(String key){ // queue.add(key); // } // // public static String pop(){ // if(!queue.isEmpty()) { // return queue.poll(); // } // return null; // } // // public static boolean isEmpty(){ // return queue.isEmpty(); // } // // public static int size(){ // return queue.size(); // } // } // Path: storm/src/main/java/com/fksm/storm/bolt/RemoveRedisBolt.java import com.fksm.utils.CuratorLockAcquire; import com.fksm.utils.RedisKeysQueueManager; import com.netflix.curator.framework.recipes.locks.InterProcessMutex; import org.apache.storm.task.OutputCollector; import org.apache.storm.task.TopologyContext; import org.apache.storm.topology.OutputFieldsDeclarer; import org.apache.storm.tuple.Tuple; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; package com.fksm.storm.bolt; /** * remove data from redis */ public class RemoveRedisBolt extends BaseRedisBasicBolt { private static final Logger logger = LoggerFactory.getLogger(RemoveRedisBolt.class);
private CuratorLockAcquire curatorLockAcquire;
wuzhongdehua/fksm
storm/src/main/java/com/fksm/storm/bolt/RemoveRedisBolt.java
// Path: storm/src/main/java/com/fksm/utils/CuratorLockAcquire.java // public class CuratorLockAcquire { // private static final Logger LOGGER = LoggerFactory.getLogger(CuratorLockAcquire.class); // // private CuratorFramework client = null; // // public CuratorLockAcquire() {} // // public synchronized CuratorFramework getCuratorClient() { // if (client == null) { // try { // String zkHostPort = ConfigPropertieUtil.getInstance().getString("curator.lock.zk.connect"); // RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3); // client = CuratorFrameworkFactory.newClient(zkHostPort, retryPolicy); // client.start(); // } catch (Exception e) { // LOGGER.error("Get curatorClient error.", e); // } // } // // return client; // } // } // // Path: storm/src/main/java/com/fksm/utils/RedisKeysQueueManager.java // public class RedisKeysQueueManager { // private static ConcurrentLinkedQueue<String> queue = new ConcurrentLinkedQueue<String>(); // // public static void add(String key){ // queue.add(key); // } // // public static String pop(){ // if(!queue.isEmpty()) { // return queue.poll(); // } // return null; // } // // public static boolean isEmpty(){ // return queue.isEmpty(); // } // // public static int size(){ // return queue.size(); // } // }
import com.fksm.utils.CuratorLockAcquire; import com.fksm.utils.RedisKeysQueueManager; import com.netflix.curator.framework.recipes.locks.InterProcessMutex; import org.apache.storm.task.OutputCollector; import org.apache.storm.task.TopologyContext; import org.apache.storm.topology.OutputFieldsDeclarer; import org.apache.storm.tuple.Tuple; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*;
package com.fksm.storm.bolt; /** * remove data from redis */ public class RemoveRedisBolt extends BaseRedisBasicBolt { private static final Logger logger = LoggerFactory.getLogger(RemoveRedisBolt.class); private CuratorLockAcquire curatorLockAcquire; @Override public void declareOutputFields(OutputFieldsDeclarer declarer) { } @Override public void prepare(Map stormConf, TopologyContext context, OutputCollector collector) { super.prepare(stormConf, context, collector); curatorLockAcquire = new CuratorLockAcquire(); Timer timer = new Timer(); timer.schedule(new SaveRedisToMysqlTimer(), nextExecTime(), 5 * 60 * 1000); } @Override public void execute(Tuple tuple) { String key = tuple.getString(0);
// Path: storm/src/main/java/com/fksm/utils/CuratorLockAcquire.java // public class CuratorLockAcquire { // private static final Logger LOGGER = LoggerFactory.getLogger(CuratorLockAcquire.class); // // private CuratorFramework client = null; // // public CuratorLockAcquire() {} // // public synchronized CuratorFramework getCuratorClient() { // if (client == null) { // try { // String zkHostPort = ConfigPropertieUtil.getInstance().getString("curator.lock.zk.connect"); // RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3); // client = CuratorFrameworkFactory.newClient(zkHostPort, retryPolicy); // client.start(); // } catch (Exception e) { // LOGGER.error("Get curatorClient error.", e); // } // } // // return client; // } // } // // Path: storm/src/main/java/com/fksm/utils/RedisKeysQueueManager.java // public class RedisKeysQueueManager { // private static ConcurrentLinkedQueue<String> queue = new ConcurrentLinkedQueue<String>(); // // public static void add(String key){ // queue.add(key); // } // // public static String pop(){ // if(!queue.isEmpty()) { // return queue.poll(); // } // return null; // } // // public static boolean isEmpty(){ // return queue.isEmpty(); // } // // public static int size(){ // return queue.size(); // } // } // Path: storm/src/main/java/com/fksm/storm/bolt/RemoveRedisBolt.java import com.fksm.utils.CuratorLockAcquire; import com.fksm.utils.RedisKeysQueueManager; import com.netflix.curator.framework.recipes.locks.InterProcessMutex; import org.apache.storm.task.OutputCollector; import org.apache.storm.task.TopologyContext; import org.apache.storm.topology.OutputFieldsDeclarer; import org.apache.storm.tuple.Tuple; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; package com.fksm.storm.bolt; /** * remove data from redis */ public class RemoveRedisBolt extends BaseRedisBasicBolt { private static final Logger logger = LoggerFactory.getLogger(RemoveRedisBolt.class); private CuratorLockAcquire curatorLockAcquire; @Override public void declareOutputFields(OutputFieldsDeclarer declarer) { } @Override public void prepare(Map stormConf, TopologyContext context, OutputCollector collector) { super.prepare(stormConf, context, collector); curatorLockAcquire = new CuratorLockAcquire(); Timer timer = new Timer(); timer.schedule(new SaveRedisToMysqlTimer(), nextExecTime(), 5 * 60 * 1000); } @Override public void execute(Tuple tuple) { String key = tuple.getString(0);
RedisKeysQueueManager.add(key);
wuzhongdehua/fksm
web-graphc/src/main/java/com/fksm/web/controller/DemoController.java
// Path: web-graphc/src/main/java/com/fksm/web/service/common/DemoService.java // public interface DemoService { // /** // * getCallers // * @return // * @throws Exception // */ // public List<HashMap> getCallers(Long startTime, Long endTime, String server_ip, String service_id) throws Exception; // } // // Path: web-graphc/src/main/java/com/fksm/web/service/global/dto/response/ResponseCode.java // public class ResponseCode { // // /** // * 通用编码:参数缺失 . // */ // public static final String COMMON_PARAMETER_MISSING = "CN001"; // // /** // * 需要重新登录 . // */ // public static final String USER_NEED_LOGIN = "UR001"; // // /** // * 用户名/密码错误 . // */ // public static final String USER_NORP_ERROR = "UR002"; // // /** // * 户登录错误 . // */ // public static final String USER_LOGIN_ERROR = "UR003"; // // /** // * 用户认证状态失效 . // */ // public static final String AUTH_USER_STATUS_ERROR = "AH002"; // // /** // * 操作成功 . // */ // public static final String OPERATE_SUCCESS = "200"; // // /** // * 操作成功 . // */ // public static final String OPERATE_NO_DATA = "NDATA"; // //==================================================================================================================================== // // public static Map<String, String> CODE_MAP = new HashMap<String,String>(); // // // 用作自动生成前端 scripts/common/messages_zh-cn.js 文件 // static{ // CODE_MAP.put(COMMON_PARAMETER_MISSING, "参数缺失"); // CODE_MAP.put(USER_NEED_LOGIN,"会话已结束,需要重新登录"); // CODE_MAP.put(USER_NORP_ERROR, "用户名或者密码错误"); // CODE_MAP.put(USER_LOGIN_ERROR, "用户登录错误"); // CODE_MAP.put(AUTH_USER_STATUS_ERROR, "用户认证状态失效"); // CODE_MAP.put(OPERATE_SUCCESS, "操作成功!"); // } // } // // Path: web-graphc/src/main/java/com/fksm/web/service/global/dto/response/ResponseDto.java // public class ResponseDto<T> implements Serializable{ // private static final long serialVersionUID = -7976564531903764830L; // // /** // * 操作结果编码 // */ // private String code = ResponseCode.OPERATE_SUCCESS; // // /** // * 响应是否正常. // */ // private boolean responseSuccess = true; // // /** // * 响应数据. // */ // private T data; // // public ResponseDto(){ // // } // // public ResponseDto(boolean responseSuccess){ // this.responseSuccess = responseSuccess; // } // // public ResponseDto(String code){ // this.code = code; // } // // public ResponseDto(String code,boolean responseSuccess){ // this.code = code; // this.responseSuccess = responseSuccess; // } // // public ResponseDto(String code,boolean responseSuccess,T data){ // this.code = code; // this.responseSuccess = responseSuccess; // this.data = data; // } // // // public String getCode() { // return code; // } // // public void setCode(String code) { // this.code = code; // } // // public boolean isResponseSuccess() { // return responseSuccess; // } // // public void setResponseSuccess(boolean responseSuccess) { // this.responseSuccess = responseSuccess; // } // // public T getData() { // return data; // } // // public void setData(T data) { // this.data = data; // } // }
import com.fksm.web.service.common.DemoService; import com.fksm.web.service.global.dto.response.ResponseCode; import com.fksm.web.service.global.dto.response.ResponseDto; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import javax.annotation.Resource; import java.util.HashMap; import java.util.List;
package com.fksm.web.controller; /** * Created by Administrator on 2016/5/7. */ @Controller @RequestMapping("/api/demo") public class DemoController { private static Logger logger = LoggerFactory.getLogger(DemoController.class); @Resource
// Path: web-graphc/src/main/java/com/fksm/web/service/common/DemoService.java // public interface DemoService { // /** // * getCallers // * @return // * @throws Exception // */ // public List<HashMap> getCallers(Long startTime, Long endTime, String server_ip, String service_id) throws Exception; // } // // Path: web-graphc/src/main/java/com/fksm/web/service/global/dto/response/ResponseCode.java // public class ResponseCode { // // /** // * 通用编码:参数缺失 . // */ // public static final String COMMON_PARAMETER_MISSING = "CN001"; // // /** // * 需要重新登录 . // */ // public static final String USER_NEED_LOGIN = "UR001"; // // /** // * 用户名/密码错误 . // */ // public static final String USER_NORP_ERROR = "UR002"; // // /** // * 户登录错误 . // */ // public static final String USER_LOGIN_ERROR = "UR003"; // // /** // * 用户认证状态失效 . // */ // public static final String AUTH_USER_STATUS_ERROR = "AH002"; // // /** // * 操作成功 . // */ // public static final String OPERATE_SUCCESS = "200"; // // /** // * 操作成功 . // */ // public static final String OPERATE_NO_DATA = "NDATA"; // //==================================================================================================================================== // // public static Map<String, String> CODE_MAP = new HashMap<String,String>(); // // // 用作自动生成前端 scripts/common/messages_zh-cn.js 文件 // static{ // CODE_MAP.put(COMMON_PARAMETER_MISSING, "参数缺失"); // CODE_MAP.put(USER_NEED_LOGIN,"会话已结束,需要重新登录"); // CODE_MAP.put(USER_NORP_ERROR, "用户名或者密码错误"); // CODE_MAP.put(USER_LOGIN_ERROR, "用户登录错误"); // CODE_MAP.put(AUTH_USER_STATUS_ERROR, "用户认证状态失效"); // CODE_MAP.put(OPERATE_SUCCESS, "操作成功!"); // } // } // // Path: web-graphc/src/main/java/com/fksm/web/service/global/dto/response/ResponseDto.java // public class ResponseDto<T> implements Serializable{ // private static final long serialVersionUID = -7976564531903764830L; // // /** // * 操作结果编码 // */ // private String code = ResponseCode.OPERATE_SUCCESS; // // /** // * 响应是否正常. // */ // private boolean responseSuccess = true; // // /** // * 响应数据. // */ // private T data; // // public ResponseDto(){ // // } // // public ResponseDto(boolean responseSuccess){ // this.responseSuccess = responseSuccess; // } // // public ResponseDto(String code){ // this.code = code; // } // // public ResponseDto(String code,boolean responseSuccess){ // this.code = code; // this.responseSuccess = responseSuccess; // } // // public ResponseDto(String code,boolean responseSuccess,T data){ // this.code = code; // this.responseSuccess = responseSuccess; // this.data = data; // } // // // public String getCode() { // return code; // } // // public void setCode(String code) { // this.code = code; // } // // public boolean isResponseSuccess() { // return responseSuccess; // } // // public void setResponseSuccess(boolean responseSuccess) { // this.responseSuccess = responseSuccess; // } // // public T getData() { // return data; // } // // public void setData(T data) { // this.data = data; // } // } // Path: web-graphc/src/main/java/com/fksm/web/controller/DemoController.java import com.fksm.web.service.common.DemoService; import com.fksm.web.service.global.dto.response.ResponseCode; import com.fksm.web.service.global.dto.response.ResponseDto; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import javax.annotation.Resource; import java.util.HashMap; import java.util.List; package com.fksm.web.controller; /** * Created by Administrator on 2016/5/7. */ @Controller @RequestMapping("/api/demo") public class DemoController { private static Logger logger = LoggerFactory.getLogger(DemoController.class); @Resource
private DemoService demoService;
wuzhongdehua/fksm
web-graphc/src/main/java/com/fksm/web/controller/DemoController.java
// Path: web-graphc/src/main/java/com/fksm/web/service/common/DemoService.java // public interface DemoService { // /** // * getCallers // * @return // * @throws Exception // */ // public List<HashMap> getCallers(Long startTime, Long endTime, String server_ip, String service_id) throws Exception; // } // // Path: web-graphc/src/main/java/com/fksm/web/service/global/dto/response/ResponseCode.java // public class ResponseCode { // // /** // * 通用编码:参数缺失 . // */ // public static final String COMMON_PARAMETER_MISSING = "CN001"; // // /** // * 需要重新登录 . // */ // public static final String USER_NEED_LOGIN = "UR001"; // // /** // * 用户名/密码错误 . // */ // public static final String USER_NORP_ERROR = "UR002"; // // /** // * 户登录错误 . // */ // public static final String USER_LOGIN_ERROR = "UR003"; // // /** // * 用户认证状态失效 . // */ // public static final String AUTH_USER_STATUS_ERROR = "AH002"; // // /** // * 操作成功 . // */ // public static final String OPERATE_SUCCESS = "200"; // // /** // * 操作成功 . // */ // public static final String OPERATE_NO_DATA = "NDATA"; // //==================================================================================================================================== // // public static Map<String, String> CODE_MAP = new HashMap<String,String>(); // // // 用作自动生成前端 scripts/common/messages_zh-cn.js 文件 // static{ // CODE_MAP.put(COMMON_PARAMETER_MISSING, "参数缺失"); // CODE_MAP.put(USER_NEED_LOGIN,"会话已结束,需要重新登录"); // CODE_MAP.put(USER_NORP_ERROR, "用户名或者密码错误"); // CODE_MAP.put(USER_LOGIN_ERROR, "用户登录错误"); // CODE_MAP.put(AUTH_USER_STATUS_ERROR, "用户认证状态失效"); // CODE_MAP.put(OPERATE_SUCCESS, "操作成功!"); // } // } // // Path: web-graphc/src/main/java/com/fksm/web/service/global/dto/response/ResponseDto.java // public class ResponseDto<T> implements Serializable{ // private static final long serialVersionUID = -7976564531903764830L; // // /** // * 操作结果编码 // */ // private String code = ResponseCode.OPERATE_SUCCESS; // // /** // * 响应是否正常. // */ // private boolean responseSuccess = true; // // /** // * 响应数据. // */ // private T data; // // public ResponseDto(){ // // } // // public ResponseDto(boolean responseSuccess){ // this.responseSuccess = responseSuccess; // } // // public ResponseDto(String code){ // this.code = code; // } // // public ResponseDto(String code,boolean responseSuccess){ // this.code = code; // this.responseSuccess = responseSuccess; // } // // public ResponseDto(String code,boolean responseSuccess,T data){ // this.code = code; // this.responseSuccess = responseSuccess; // this.data = data; // } // // // public String getCode() { // return code; // } // // public void setCode(String code) { // this.code = code; // } // // public boolean isResponseSuccess() { // return responseSuccess; // } // // public void setResponseSuccess(boolean responseSuccess) { // this.responseSuccess = responseSuccess; // } // // public T getData() { // return data; // } // // public void setData(T data) { // this.data = data; // } // }
import com.fksm.web.service.common.DemoService; import com.fksm.web.service.global.dto.response.ResponseCode; import com.fksm.web.service.global.dto.response.ResponseDto; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import javax.annotation.Resource; import java.util.HashMap; import java.util.List;
package com.fksm.web.controller; /** * Created by Administrator on 2016/5/7. */ @Controller @RequestMapping("/api/demo") public class DemoController { private static Logger logger = LoggerFactory.getLogger(DemoController.class); @Resource private DemoService demoService; /** * 描述: 保存 . * @return * @throws Exception */ @RequestMapping("/list") @ResponseBody
// Path: web-graphc/src/main/java/com/fksm/web/service/common/DemoService.java // public interface DemoService { // /** // * getCallers // * @return // * @throws Exception // */ // public List<HashMap> getCallers(Long startTime, Long endTime, String server_ip, String service_id) throws Exception; // } // // Path: web-graphc/src/main/java/com/fksm/web/service/global/dto/response/ResponseCode.java // public class ResponseCode { // // /** // * 通用编码:参数缺失 . // */ // public static final String COMMON_PARAMETER_MISSING = "CN001"; // // /** // * 需要重新登录 . // */ // public static final String USER_NEED_LOGIN = "UR001"; // // /** // * 用户名/密码错误 . // */ // public static final String USER_NORP_ERROR = "UR002"; // // /** // * 户登录错误 . // */ // public static final String USER_LOGIN_ERROR = "UR003"; // // /** // * 用户认证状态失效 . // */ // public static final String AUTH_USER_STATUS_ERROR = "AH002"; // // /** // * 操作成功 . // */ // public static final String OPERATE_SUCCESS = "200"; // // /** // * 操作成功 . // */ // public static final String OPERATE_NO_DATA = "NDATA"; // //==================================================================================================================================== // // public static Map<String, String> CODE_MAP = new HashMap<String,String>(); // // // 用作自动生成前端 scripts/common/messages_zh-cn.js 文件 // static{ // CODE_MAP.put(COMMON_PARAMETER_MISSING, "参数缺失"); // CODE_MAP.put(USER_NEED_LOGIN,"会话已结束,需要重新登录"); // CODE_MAP.put(USER_NORP_ERROR, "用户名或者密码错误"); // CODE_MAP.put(USER_LOGIN_ERROR, "用户登录错误"); // CODE_MAP.put(AUTH_USER_STATUS_ERROR, "用户认证状态失效"); // CODE_MAP.put(OPERATE_SUCCESS, "操作成功!"); // } // } // // Path: web-graphc/src/main/java/com/fksm/web/service/global/dto/response/ResponseDto.java // public class ResponseDto<T> implements Serializable{ // private static final long serialVersionUID = -7976564531903764830L; // // /** // * 操作结果编码 // */ // private String code = ResponseCode.OPERATE_SUCCESS; // // /** // * 响应是否正常. // */ // private boolean responseSuccess = true; // // /** // * 响应数据. // */ // private T data; // // public ResponseDto(){ // // } // // public ResponseDto(boolean responseSuccess){ // this.responseSuccess = responseSuccess; // } // // public ResponseDto(String code){ // this.code = code; // } // // public ResponseDto(String code,boolean responseSuccess){ // this.code = code; // this.responseSuccess = responseSuccess; // } // // public ResponseDto(String code,boolean responseSuccess,T data){ // this.code = code; // this.responseSuccess = responseSuccess; // this.data = data; // } // // // public String getCode() { // return code; // } // // public void setCode(String code) { // this.code = code; // } // // public boolean isResponseSuccess() { // return responseSuccess; // } // // public void setResponseSuccess(boolean responseSuccess) { // this.responseSuccess = responseSuccess; // } // // public T getData() { // return data; // } // // public void setData(T data) { // this.data = data; // } // } // Path: web-graphc/src/main/java/com/fksm/web/controller/DemoController.java import com.fksm.web.service.common.DemoService; import com.fksm.web.service.global.dto.response.ResponseCode; import com.fksm.web.service.global.dto.response.ResponseDto; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import javax.annotation.Resource; import java.util.HashMap; import java.util.List; package com.fksm.web.controller; /** * Created by Administrator on 2016/5/7. */ @Controller @RequestMapping("/api/demo") public class DemoController { private static Logger logger = LoggerFactory.getLogger(DemoController.class); @Resource private DemoService demoService; /** * 描述: 保存 . * @return * @throws Exception */ @RequestMapping("/list") @ResponseBody
public ResponseDto<List<HashMap>> list
wuzhongdehua/fksm
flume/src/main/java/com/fksm/flume/interceptor/CleanAndToJsonInterceptor.java
// Path: common/src/main/java/com/fksm/common/util/Constants.java // public class Constants { // /** The Constant REGEX. */ // public static final String REGEX_UUID = "regex.uuid"; // public static final String REGEX_IP = "regex.ip"; // public static final String REGEX_TIME = "regex.time"; // // public static final int TYPE_CALLER_INFO = 1; // public static final int TYPE_RESP_PARAM = 2; // public static final int TYPE_REQ_PARAM = 3; // public static final int TYPE_RESP_TIME = 4; // public static final int TYPE_SERVICE_INFO = 5; // // public static final String REDIS_SERVER_KEY = "SERVER"; // // public static final String REDIS_SERVER_SERVICE_PREFIX = "SERVER_SERVICE_"; // public static final String REDIS_SERVICE_REQUEST_PREFIX = "SERVICE_REQUEST_"; // public static final String REDIS_TIME_REQUESTS_PREFIX = "TIME_REQUESTS_"; // //server->service->requests // public static final String REDIS_SERVER_SERVICE_REQUEST_PREFIX = "SERVER_SERVICE_REQUEST_"; // // public static final String REDIS_SERVICE_COSTS_PREFIX = "SERVICE_COSTS_"; // public static final String REDIS_SERVICE_CALLERS_PREFIX = "SERVICE_CALLERS_"; // public static final String REDIS_SERVICE_CODES_PREFIX = "SERVICE_CODES_"; // // public static final String REDIS_SERVICE_REQUEST_CALLER_PREFIX = "SERVICE_REQUEST_CALLER_"; // public static final String REDIS_SERVER_SERVICE_COST_PREFIX = "SERVER_SERVICE_COST_"; // public static final String REDIS_SERVICE_REQUEST_CODE_PREFIX = "SERVICE_REQUEST_CODE_"; // // public static final String REDIS_SERVER_PREFIX = "S_SERVER_SERVICE_REQUEST_"; // public static final String REDIS_SERVER_COSTS_PREFIX = "S_SERVER_SERVICE_COSTS_"; // public static final String REDIS_SERVER_CALLER_PREFIX = "S_SERVER_SERVICE_CALLER_"; // public static final String REDIS_SERVER_CODE_PREFIX = "S_SERVER_SERVICE_CODE_"; // // public static final String REDIS_TIMELINE_KEY = "TIMELINE_KEY"; // // public static final Integer CODE_SUCESS = 100; // }
import com.alibaba.fastjson.JSON; import com.fksm.common.dto.*; import com.fksm.common.util.Constants; import com.google.common.base.Charsets; import com.google.common.collect.Lists; import org.apache.flume.Context; import org.apache.flume.Event; import org.apache.flume.interceptor.Interceptor; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern;
logger.error("error get result : {} from log.", e); return null; } } @Override public List<Event> intercept(List<Event> events) { List<Event> out = Lists.newArrayList(); for (Event event : events) { Event outEvent = intercept(event); if (outEvent != null) { out.add(outEvent); } } return out; } @Override public void close() { // no-op } public static class Builder implements Interceptor.Builder { private Pattern uuid; private Pattern ip; private Pattern time; @Override public void configure(Context context) {
// Path: common/src/main/java/com/fksm/common/util/Constants.java // public class Constants { // /** The Constant REGEX. */ // public static final String REGEX_UUID = "regex.uuid"; // public static final String REGEX_IP = "regex.ip"; // public static final String REGEX_TIME = "regex.time"; // // public static final int TYPE_CALLER_INFO = 1; // public static final int TYPE_RESP_PARAM = 2; // public static final int TYPE_REQ_PARAM = 3; // public static final int TYPE_RESP_TIME = 4; // public static final int TYPE_SERVICE_INFO = 5; // // public static final String REDIS_SERVER_KEY = "SERVER"; // // public static final String REDIS_SERVER_SERVICE_PREFIX = "SERVER_SERVICE_"; // public static final String REDIS_SERVICE_REQUEST_PREFIX = "SERVICE_REQUEST_"; // public static final String REDIS_TIME_REQUESTS_PREFIX = "TIME_REQUESTS_"; // //server->service->requests // public static final String REDIS_SERVER_SERVICE_REQUEST_PREFIX = "SERVER_SERVICE_REQUEST_"; // // public static final String REDIS_SERVICE_COSTS_PREFIX = "SERVICE_COSTS_"; // public static final String REDIS_SERVICE_CALLERS_PREFIX = "SERVICE_CALLERS_"; // public static final String REDIS_SERVICE_CODES_PREFIX = "SERVICE_CODES_"; // // public static final String REDIS_SERVICE_REQUEST_CALLER_PREFIX = "SERVICE_REQUEST_CALLER_"; // public static final String REDIS_SERVER_SERVICE_COST_PREFIX = "SERVER_SERVICE_COST_"; // public static final String REDIS_SERVICE_REQUEST_CODE_PREFIX = "SERVICE_REQUEST_CODE_"; // // public static final String REDIS_SERVER_PREFIX = "S_SERVER_SERVICE_REQUEST_"; // public static final String REDIS_SERVER_COSTS_PREFIX = "S_SERVER_SERVICE_COSTS_"; // public static final String REDIS_SERVER_CALLER_PREFIX = "S_SERVER_SERVICE_CALLER_"; // public static final String REDIS_SERVER_CODE_PREFIX = "S_SERVER_SERVICE_CODE_"; // // public static final String REDIS_TIMELINE_KEY = "TIMELINE_KEY"; // // public static final Integer CODE_SUCESS = 100; // } // Path: flume/src/main/java/com/fksm/flume/interceptor/CleanAndToJsonInterceptor.java import com.alibaba.fastjson.JSON; import com.fksm.common.dto.*; import com.fksm.common.util.Constants; import com.google.common.base.Charsets; import com.google.common.collect.Lists; import org.apache.flume.Context; import org.apache.flume.Event; import org.apache.flume.interceptor.Interceptor; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; logger.error("error get result : {} from log.", e); return null; } } @Override public List<Event> intercept(List<Event> events) { List<Event> out = Lists.newArrayList(); for (Event event : events) { Event outEvent = intercept(event); if (outEvent != null) { out.add(outEvent); } } return out; } @Override public void close() { // no-op } public static class Builder implements Interceptor.Builder { private Pattern uuid; private Pattern ip; private Pattern time; @Override public void configure(Context context) {
uuid = Pattern.compile(context.getString(Constants.REGEX_UUID, ""), Pattern.MULTILINE);
wuzhongdehua/fksm
storm/src/main/java/com/fksm/storm/topology/KafkaTopology.java
// Path: storm/src/main/java/com/fksm/storm/hdfs/action/MoveStormToLogAction.java // public class MoveStormToLogAction implements RotationAction { // private static final Logger logger = LoggerFactory.getLogger(MoveStormToLogAction.class); // // private String destination; // // public MoveStormToLogAction withDestination(String destDir){ // destination = destDir; // return this; // } // // @Override // public void execute(FileSystem fileSystem, Path filePath) throws IOException { // Path destPath = new Path(destination, filePath.getName()); // logger.info("Moving file {} to {}", filePath, destPath); // boolean success = fileSystem.rename(filePath, destPath); // return; // } // } // // Path: storm/src/main/java/com/fksm/utils/ConfigPropertieUtil.java // public class ConfigPropertieUtil { // // private static final Logger LOGGER = LoggerFactory.getLogger(ConfigPropertieUtil.class); // // private static Config config; // // static { // config = ConfigFactory.load(); // } // // public static Config getInstance(){ // return config; // } // // public static Config getInstance(String configFile){ // config = ConfigFactory.load(configFile); // config.checkValid(ConfigFactory.defaultReference(), "simple-lib"); // return config; // } // }
import com.fksm.storm.bolt.*; import com.fksm.storm.hdfs.action.MoveStormToLogAction; import com.fksm.utils.ConfigPropertieUtil; import org.apache.hadoop.io.SequenceFile; import org.apache.storm.Config; import org.apache.storm.LocalCluster; import org.apache.storm.StormSubmitter; import org.apache.storm.generated.AlreadyAliveException; import org.apache.storm.generated.AuthorizationException; import org.apache.storm.generated.InvalidTopologyException; import org.apache.storm.hdfs.bolt.HdfsBolt; import org.apache.storm.hdfs.bolt.SequenceFileBolt; import org.apache.storm.hdfs.bolt.format.*; import org.apache.storm.hdfs.bolt.rotation.FileRotationPolicy; import org.apache.storm.hdfs.bolt.rotation.FileSizeRotationPolicy; import org.apache.storm.hdfs.bolt.rotation.FileSizeRotationPolicy.*; import org.apache.storm.hdfs.bolt.sync.CountSyncPolicy; import org.apache.storm.hdfs.bolt.sync.SyncPolicy; import org.apache.storm.kafka.*; import org.apache.storm.spout.SchemeAsMultiScheme; import org.apache.storm.topology.TopologyBuilder; import org.apache.storm.topology.base.BaseWindowedBolt.*; import org.apache.storm.tuple.Fields; import java.util.Arrays; import java.util.concurrent.TimeUnit;
package com.fksm.storm.topology; /** * Created by Administrator on 2016/4/21 0021. */ public class KafkaTopology { public static void main(String[] args) throws AlreadyAliveException, InvalidTopologyException, InterruptedException, AuthorizationException {
// Path: storm/src/main/java/com/fksm/storm/hdfs/action/MoveStormToLogAction.java // public class MoveStormToLogAction implements RotationAction { // private static final Logger logger = LoggerFactory.getLogger(MoveStormToLogAction.class); // // private String destination; // // public MoveStormToLogAction withDestination(String destDir){ // destination = destDir; // return this; // } // // @Override // public void execute(FileSystem fileSystem, Path filePath) throws IOException { // Path destPath = new Path(destination, filePath.getName()); // logger.info("Moving file {} to {}", filePath, destPath); // boolean success = fileSystem.rename(filePath, destPath); // return; // } // } // // Path: storm/src/main/java/com/fksm/utils/ConfigPropertieUtil.java // public class ConfigPropertieUtil { // // private static final Logger LOGGER = LoggerFactory.getLogger(ConfigPropertieUtil.class); // // private static Config config; // // static { // config = ConfigFactory.load(); // } // // public static Config getInstance(){ // return config; // } // // public static Config getInstance(String configFile){ // config = ConfigFactory.load(configFile); // config.checkValid(ConfigFactory.defaultReference(), "simple-lib"); // return config; // } // } // Path: storm/src/main/java/com/fksm/storm/topology/KafkaTopology.java import com.fksm.storm.bolt.*; import com.fksm.storm.hdfs.action.MoveStormToLogAction; import com.fksm.utils.ConfigPropertieUtil; import org.apache.hadoop.io.SequenceFile; import org.apache.storm.Config; import org.apache.storm.LocalCluster; import org.apache.storm.StormSubmitter; import org.apache.storm.generated.AlreadyAliveException; import org.apache.storm.generated.AuthorizationException; import org.apache.storm.generated.InvalidTopologyException; import org.apache.storm.hdfs.bolt.HdfsBolt; import org.apache.storm.hdfs.bolt.SequenceFileBolt; import org.apache.storm.hdfs.bolt.format.*; import org.apache.storm.hdfs.bolt.rotation.FileRotationPolicy; import org.apache.storm.hdfs.bolt.rotation.FileSizeRotationPolicy; import org.apache.storm.hdfs.bolt.rotation.FileSizeRotationPolicy.*; import org.apache.storm.hdfs.bolt.sync.CountSyncPolicy; import org.apache.storm.hdfs.bolt.sync.SyncPolicy; import org.apache.storm.kafka.*; import org.apache.storm.spout.SchemeAsMultiScheme; import org.apache.storm.topology.TopologyBuilder; import org.apache.storm.topology.base.BaseWindowedBolt.*; import org.apache.storm.tuple.Fields; import java.util.Arrays; import java.util.concurrent.TimeUnit; package com.fksm.storm.topology; /** * Created by Administrator on 2016/4/21 0021. */ public class KafkaTopology { public static void main(String[] args) throws AlreadyAliveException, InvalidTopologyException, InterruptedException, AuthorizationException {
com.typesafe.config.Config config = ConfigPropertieUtil.getInstance();
wuzhongdehua/fksm
storm/src/main/java/com/fksm/storm/topology/KafkaTopology.java
// Path: storm/src/main/java/com/fksm/storm/hdfs/action/MoveStormToLogAction.java // public class MoveStormToLogAction implements RotationAction { // private static final Logger logger = LoggerFactory.getLogger(MoveStormToLogAction.class); // // private String destination; // // public MoveStormToLogAction withDestination(String destDir){ // destination = destDir; // return this; // } // // @Override // public void execute(FileSystem fileSystem, Path filePath) throws IOException { // Path destPath = new Path(destination, filePath.getName()); // logger.info("Moving file {} to {}", filePath, destPath); // boolean success = fileSystem.rename(filePath, destPath); // return; // } // } // // Path: storm/src/main/java/com/fksm/utils/ConfigPropertieUtil.java // public class ConfigPropertieUtil { // // private static final Logger LOGGER = LoggerFactory.getLogger(ConfigPropertieUtil.class); // // private static Config config; // // static { // config = ConfigFactory.load(); // } // // public static Config getInstance(){ // return config; // } // // public static Config getInstance(String configFile){ // config = ConfigFactory.load(configFile); // config.checkValid(ConfigFactory.defaultReference(), "simple-lib"); // return config; // } // }
import com.fksm.storm.bolt.*; import com.fksm.storm.hdfs.action.MoveStormToLogAction; import com.fksm.utils.ConfigPropertieUtil; import org.apache.hadoop.io.SequenceFile; import org.apache.storm.Config; import org.apache.storm.LocalCluster; import org.apache.storm.StormSubmitter; import org.apache.storm.generated.AlreadyAliveException; import org.apache.storm.generated.AuthorizationException; import org.apache.storm.generated.InvalidTopologyException; import org.apache.storm.hdfs.bolt.HdfsBolt; import org.apache.storm.hdfs.bolt.SequenceFileBolt; import org.apache.storm.hdfs.bolt.format.*; import org.apache.storm.hdfs.bolt.rotation.FileRotationPolicy; import org.apache.storm.hdfs.bolt.rotation.FileSizeRotationPolicy; import org.apache.storm.hdfs.bolt.rotation.FileSizeRotationPolicy.*; import org.apache.storm.hdfs.bolt.sync.CountSyncPolicy; import org.apache.storm.hdfs.bolt.sync.SyncPolicy; import org.apache.storm.kafka.*; import org.apache.storm.spout.SchemeAsMultiScheme; import org.apache.storm.topology.TopologyBuilder; import org.apache.storm.topology.base.BaseWindowedBolt.*; import org.apache.storm.tuple.Fields; import java.util.Arrays; import java.util.concurrent.TimeUnit;
conf.setMaxTaskParallelism(numWorkers); LocalCluster cluster = new LocalCluster(); cluster.submitTopology(name, conf, builder.createTopology()); Thread.sleep(60000); cluster.shutdown(); } } private static HdfsBolt buildHdfsBolt(String hdfsUrl,String prefix, Fields fields){ // use "|" instead of "," for field delimiter RecordFormat format = new DelimitedRecordFormat() .withFieldDelimiter(" : ").withFields(fields); // sync the filesystem after every 1k tuples SyncPolicy syncPolicy = new CountSyncPolicy(1000); // rotate files FileRotationPolicy rotationPolicy = new FileSizeRotationPolicy(5.0f, Units.MB); FileNameFormat fileNameFormat = new DefaultFileNameFormat() .withPath("/storm/").withPrefix(prefix).withExtension(".seq"); HdfsBolt hdfsBolt = new HdfsBolt() .withFsUrl(hdfsUrl) .withFileNameFormat(fileNameFormat) .withRecordFormat(format) .withRotationPolicy(rotationPolicy) .withSyncPolicy(syncPolicy) .withRetryCount(5)
// Path: storm/src/main/java/com/fksm/storm/hdfs/action/MoveStormToLogAction.java // public class MoveStormToLogAction implements RotationAction { // private static final Logger logger = LoggerFactory.getLogger(MoveStormToLogAction.class); // // private String destination; // // public MoveStormToLogAction withDestination(String destDir){ // destination = destDir; // return this; // } // // @Override // public void execute(FileSystem fileSystem, Path filePath) throws IOException { // Path destPath = new Path(destination, filePath.getName()); // logger.info("Moving file {} to {}", filePath, destPath); // boolean success = fileSystem.rename(filePath, destPath); // return; // } // } // // Path: storm/src/main/java/com/fksm/utils/ConfigPropertieUtil.java // public class ConfigPropertieUtil { // // private static final Logger LOGGER = LoggerFactory.getLogger(ConfigPropertieUtil.class); // // private static Config config; // // static { // config = ConfigFactory.load(); // } // // public static Config getInstance(){ // return config; // } // // public static Config getInstance(String configFile){ // config = ConfigFactory.load(configFile); // config.checkValid(ConfigFactory.defaultReference(), "simple-lib"); // return config; // } // } // Path: storm/src/main/java/com/fksm/storm/topology/KafkaTopology.java import com.fksm.storm.bolt.*; import com.fksm.storm.hdfs.action.MoveStormToLogAction; import com.fksm.utils.ConfigPropertieUtil; import org.apache.hadoop.io.SequenceFile; import org.apache.storm.Config; import org.apache.storm.LocalCluster; import org.apache.storm.StormSubmitter; import org.apache.storm.generated.AlreadyAliveException; import org.apache.storm.generated.AuthorizationException; import org.apache.storm.generated.InvalidTopologyException; import org.apache.storm.hdfs.bolt.HdfsBolt; import org.apache.storm.hdfs.bolt.SequenceFileBolt; import org.apache.storm.hdfs.bolt.format.*; import org.apache.storm.hdfs.bolt.rotation.FileRotationPolicy; import org.apache.storm.hdfs.bolt.rotation.FileSizeRotationPolicy; import org.apache.storm.hdfs.bolt.rotation.FileSizeRotationPolicy.*; import org.apache.storm.hdfs.bolt.sync.CountSyncPolicy; import org.apache.storm.hdfs.bolt.sync.SyncPolicy; import org.apache.storm.kafka.*; import org.apache.storm.spout.SchemeAsMultiScheme; import org.apache.storm.topology.TopologyBuilder; import org.apache.storm.topology.base.BaseWindowedBolt.*; import org.apache.storm.tuple.Fields; import java.util.Arrays; import java.util.concurrent.TimeUnit; conf.setMaxTaskParallelism(numWorkers); LocalCluster cluster = new LocalCluster(); cluster.submitTopology(name, conf, builder.createTopology()); Thread.sleep(60000); cluster.shutdown(); } } private static HdfsBolt buildHdfsBolt(String hdfsUrl,String prefix, Fields fields){ // use "|" instead of "," for field delimiter RecordFormat format = new DelimitedRecordFormat() .withFieldDelimiter(" : ").withFields(fields); // sync the filesystem after every 1k tuples SyncPolicy syncPolicy = new CountSyncPolicy(1000); // rotate files FileRotationPolicy rotationPolicy = new FileSizeRotationPolicy(5.0f, Units.MB); FileNameFormat fileNameFormat = new DefaultFileNameFormat() .withPath("/storm/").withPrefix(prefix).withExtension(".seq"); HdfsBolt hdfsBolt = new HdfsBolt() .withFsUrl(hdfsUrl) .withFileNameFormat(fileNameFormat) .withRecordFormat(format) .withRotationPolicy(rotationPolicy) .withSyncPolicy(syncPolicy) .withRetryCount(5)
.addRotationAction(new MoveStormToLogAction().withDestination("/log"));
wuzhongdehua/fksm
storm/src/main/java/com/fksm/utils/CacheManager.java
// Path: common/src/main/java/com/fksm/common/util/Constants.java // public class Constants { // /** The Constant REGEX. */ // public static final String REGEX_UUID = "regex.uuid"; // public static final String REGEX_IP = "regex.ip"; // public static final String REGEX_TIME = "regex.time"; // // public static final int TYPE_CALLER_INFO = 1; // public static final int TYPE_RESP_PARAM = 2; // public static final int TYPE_REQ_PARAM = 3; // public static final int TYPE_RESP_TIME = 4; // public static final int TYPE_SERVICE_INFO = 5; // // public static final String REDIS_SERVER_KEY = "SERVER"; // // public static final String REDIS_SERVER_SERVICE_PREFIX = "SERVER_SERVICE_"; // public static final String REDIS_SERVICE_REQUEST_PREFIX = "SERVICE_REQUEST_"; // public static final String REDIS_TIME_REQUESTS_PREFIX = "TIME_REQUESTS_"; // //server->service->requests // public static final String REDIS_SERVER_SERVICE_REQUEST_PREFIX = "SERVER_SERVICE_REQUEST_"; // // public static final String REDIS_SERVICE_COSTS_PREFIX = "SERVICE_COSTS_"; // public static final String REDIS_SERVICE_CALLERS_PREFIX = "SERVICE_CALLERS_"; // public static final String REDIS_SERVICE_CODES_PREFIX = "SERVICE_CODES_"; // // public static final String REDIS_SERVICE_REQUEST_CALLER_PREFIX = "SERVICE_REQUEST_CALLER_"; // public static final String REDIS_SERVER_SERVICE_COST_PREFIX = "SERVER_SERVICE_COST_"; // public static final String REDIS_SERVICE_REQUEST_CODE_PREFIX = "SERVICE_REQUEST_CODE_"; // // public static final String REDIS_SERVER_PREFIX = "S_SERVER_SERVICE_REQUEST_"; // public static final String REDIS_SERVER_COSTS_PREFIX = "S_SERVER_SERVICE_COSTS_"; // public static final String REDIS_SERVER_CALLER_PREFIX = "S_SERVER_SERVICE_CALLER_"; // public static final String REDIS_SERVER_CODE_PREFIX = "S_SERVER_SERVICE_CODE_"; // // public static final String REDIS_TIMELINE_KEY = "TIMELINE_KEY"; // // public static final Integer CODE_SUCESS = 100; // }
import com.alibaba.fastjson.JSON; import com.fksm.common.util.Constants; import com.typesafe.config.Config; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*;
public void putServiceRequestsCache(String service_id, String request_id){ ArrayList<String> requests = service_requests.get(service_id); if(requests == null){ ArrayList<String> d = new ArrayList<>(); d.add(request_id); service_requests.put(service_id, d); }else{ requests.add(request_id); } } public Map<String, HashMap<String, String>> getServiceCallersCache(){ return service_callers; } public void putServiceCallersCache(String service_id, String request_id, String caller_ip){ HashMap<String, String> requests = service_callers.get(service_id); if(requests == null){ HashMap<String, String> d = new HashMap<String, String>(); d.put(request_id, caller_ip); service_callers.put(service_id, d); }else{ requests.put(request_id, caller_ip); } } private void saveServiceCallers(){ if(service_callers.size() > 0) { for (String service:service_callers.keySet()){
// Path: common/src/main/java/com/fksm/common/util/Constants.java // public class Constants { // /** The Constant REGEX. */ // public static final String REGEX_UUID = "regex.uuid"; // public static final String REGEX_IP = "regex.ip"; // public static final String REGEX_TIME = "regex.time"; // // public static final int TYPE_CALLER_INFO = 1; // public static final int TYPE_RESP_PARAM = 2; // public static final int TYPE_REQ_PARAM = 3; // public static final int TYPE_RESP_TIME = 4; // public static final int TYPE_SERVICE_INFO = 5; // // public static final String REDIS_SERVER_KEY = "SERVER"; // // public static final String REDIS_SERVER_SERVICE_PREFIX = "SERVER_SERVICE_"; // public static final String REDIS_SERVICE_REQUEST_PREFIX = "SERVICE_REQUEST_"; // public static final String REDIS_TIME_REQUESTS_PREFIX = "TIME_REQUESTS_"; // //server->service->requests // public static final String REDIS_SERVER_SERVICE_REQUEST_PREFIX = "SERVER_SERVICE_REQUEST_"; // // public static final String REDIS_SERVICE_COSTS_PREFIX = "SERVICE_COSTS_"; // public static final String REDIS_SERVICE_CALLERS_PREFIX = "SERVICE_CALLERS_"; // public static final String REDIS_SERVICE_CODES_PREFIX = "SERVICE_CODES_"; // // public static final String REDIS_SERVICE_REQUEST_CALLER_PREFIX = "SERVICE_REQUEST_CALLER_"; // public static final String REDIS_SERVER_SERVICE_COST_PREFIX = "SERVER_SERVICE_COST_"; // public static final String REDIS_SERVICE_REQUEST_CODE_PREFIX = "SERVICE_REQUEST_CODE_"; // // public static final String REDIS_SERVER_PREFIX = "S_SERVER_SERVICE_REQUEST_"; // public static final String REDIS_SERVER_COSTS_PREFIX = "S_SERVER_SERVICE_COSTS_"; // public static final String REDIS_SERVER_CALLER_PREFIX = "S_SERVER_SERVICE_CALLER_"; // public static final String REDIS_SERVER_CODE_PREFIX = "S_SERVER_SERVICE_CODE_"; // // public static final String REDIS_TIMELINE_KEY = "TIMELINE_KEY"; // // public static final Integer CODE_SUCESS = 100; // } // Path: storm/src/main/java/com/fksm/utils/CacheManager.java import com.alibaba.fastjson.JSON; import com.fksm.common.util.Constants; import com.typesafe.config.Config; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; public void putServiceRequestsCache(String service_id, String request_id){ ArrayList<String> requests = service_requests.get(service_id); if(requests == null){ ArrayList<String> d = new ArrayList<>(); d.add(request_id); service_requests.put(service_id, d); }else{ requests.add(request_id); } } public Map<String, HashMap<String, String>> getServiceCallersCache(){ return service_callers; } public void putServiceCallersCache(String service_id, String request_id, String caller_ip){ HashMap<String, String> requests = service_callers.get(service_id); if(requests == null){ HashMap<String, String> d = new HashMap<String, String>(); d.put(request_id, caller_ip); service_callers.put(service_id, d); }else{ requests.put(request_id, caller_ip); } } private void saveServiceCallers(){ if(service_callers.size() > 0) { for (String service:service_callers.keySet()){
String key = Constants.REDIS_SERVICE_CODES_PREFIX + service;
wuzhongdehua/fksm
storm/src/main/java/com/fksm/storm/bolt/SaveHDFSBold.java
// Path: common/src/main/java/com/fksm/common/util/Constants.java // public class Constants { // /** The Constant REGEX. */ // public static final String REGEX_UUID = "regex.uuid"; // public static final String REGEX_IP = "regex.ip"; // public static final String REGEX_TIME = "regex.time"; // // public static final int TYPE_CALLER_INFO = 1; // public static final int TYPE_RESP_PARAM = 2; // public static final int TYPE_REQ_PARAM = 3; // public static final int TYPE_RESP_TIME = 4; // public static final int TYPE_SERVICE_INFO = 5; // // public static final String REDIS_SERVER_KEY = "SERVER"; // // public static final String REDIS_SERVER_SERVICE_PREFIX = "SERVER_SERVICE_"; // public static final String REDIS_SERVICE_REQUEST_PREFIX = "SERVICE_REQUEST_"; // public static final String REDIS_TIME_REQUESTS_PREFIX = "TIME_REQUESTS_"; // //server->service->requests // public static final String REDIS_SERVER_SERVICE_REQUEST_PREFIX = "SERVER_SERVICE_REQUEST_"; // // public static final String REDIS_SERVICE_COSTS_PREFIX = "SERVICE_COSTS_"; // public static final String REDIS_SERVICE_CALLERS_PREFIX = "SERVICE_CALLERS_"; // public static final String REDIS_SERVICE_CODES_PREFIX = "SERVICE_CODES_"; // // public static final String REDIS_SERVICE_REQUEST_CALLER_PREFIX = "SERVICE_REQUEST_CALLER_"; // public static final String REDIS_SERVER_SERVICE_COST_PREFIX = "SERVER_SERVICE_COST_"; // public static final String REDIS_SERVICE_REQUEST_CODE_PREFIX = "SERVICE_REQUEST_CODE_"; // // public static final String REDIS_SERVER_PREFIX = "S_SERVER_SERVICE_REQUEST_"; // public static final String REDIS_SERVER_COSTS_PREFIX = "S_SERVER_SERVICE_COSTS_"; // public static final String REDIS_SERVER_CALLER_PREFIX = "S_SERVER_SERVICE_CALLER_"; // public static final String REDIS_SERVER_CODE_PREFIX = "S_SERVER_SERVICE_CODE_"; // // public static final String REDIS_TIMELINE_KEY = "TIMELINE_KEY"; // // public static final Integer CODE_SUCESS = 100; // }
import com.alibaba.fastjson.JSONObject; import com.fksm.common.util.Constants; import org.apache.storm.task.OutputCollector; import org.apache.storm.task.TopologyContext; import org.apache.storm.topology.OutputFieldsDeclarer; import org.apache.storm.topology.base.BaseRichBolt; import org.apache.storm.tuple.Fields; import org.apache.storm.tuple.Tuple; import org.apache.storm.tuple.Values; import java.util.Map;
package com.fksm.storm.bolt; /** * Created by root on 16-4-28. */ public class SaveHDFSBold extends BaseRichBolt { private OutputCollector collector; @Override public void prepare(Map stormConf, TopologyContext context, OutputCollector collector) { this.collector = collector; } @Override public void execute(Tuple tuple) { Integer type = tuple.getIntegerByField("type"); JSONObject data = (JSONObject)tuple.getValueByField("data"); String res = buildCallerInfo(data); switch (type){
// Path: common/src/main/java/com/fksm/common/util/Constants.java // public class Constants { // /** The Constant REGEX. */ // public static final String REGEX_UUID = "regex.uuid"; // public static final String REGEX_IP = "regex.ip"; // public static final String REGEX_TIME = "regex.time"; // // public static final int TYPE_CALLER_INFO = 1; // public static final int TYPE_RESP_PARAM = 2; // public static final int TYPE_REQ_PARAM = 3; // public static final int TYPE_RESP_TIME = 4; // public static final int TYPE_SERVICE_INFO = 5; // // public static final String REDIS_SERVER_KEY = "SERVER"; // // public static final String REDIS_SERVER_SERVICE_PREFIX = "SERVER_SERVICE_"; // public static final String REDIS_SERVICE_REQUEST_PREFIX = "SERVICE_REQUEST_"; // public static final String REDIS_TIME_REQUESTS_PREFIX = "TIME_REQUESTS_"; // //server->service->requests // public static final String REDIS_SERVER_SERVICE_REQUEST_PREFIX = "SERVER_SERVICE_REQUEST_"; // // public static final String REDIS_SERVICE_COSTS_PREFIX = "SERVICE_COSTS_"; // public static final String REDIS_SERVICE_CALLERS_PREFIX = "SERVICE_CALLERS_"; // public static final String REDIS_SERVICE_CODES_PREFIX = "SERVICE_CODES_"; // // public static final String REDIS_SERVICE_REQUEST_CALLER_PREFIX = "SERVICE_REQUEST_CALLER_"; // public static final String REDIS_SERVER_SERVICE_COST_PREFIX = "SERVER_SERVICE_COST_"; // public static final String REDIS_SERVICE_REQUEST_CODE_PREFIX = "SERVICE_REQUEST_CODE_"; // // public static final String REDIS_SERVER_PREFIX = "S_SERVER_SERVICE_REQUEST_"; // public static final String REDIS_SERVER_COSTS_PREFIX = "S_SERVER_SERVICE_COSTS_"; // public static final String REDIS_SERVER_CALLER_PREFIX = "S_SERVER_SERVICE_CALLER_"; // public static final String REDIS_SERVER_CODE_PREFIX = "S_SERVER_SERVICE_CODE_"; // // public static final String REDIS_TIMELINE_KEY = "TIMELINE_KEY"; // // public static final Integer CODE_SUCESS = 100; // } // Path: storm/src/main/java/com/fksm/storm/bolt/SaveHDFSBold.java import com.alibaba.fastjson.JSONObject; import com.fksm.common.util.Constants; import org.apache.storm.task.OutputCollector; import org.apache.storm.task.TopologyContext; import org.apache.storm.topology.OutputFieldsDeclarer; import org.apache.storm.topology.base.BaseRichBolt; import org.apache.storm.tuple.Fields; import org.apache.storm.tuple.Tuple; import org.apache.storm.tuple.Values; import java.util.Map; package com.fksm.storm.bolt; /** * Created by root on 16-4-28. */ public class SaveHDFSBold extends BaseRichBolt { private OutputCollector collector; @Override public void prepare(Map stormConf, TopologyContext context, OutputCollector collector) { this.collector = collector; } @Override public void execute(Tuple tuple) { Integer type = tuple.getIntegerByField("type"); JSONObject data = (JSONObject)tuple.getValueByField("data"); String res = buildCallerInfo(data); switch (type){
case Constants.TYPE_CALLER_INFO:
wuzhongdehua/fksm
web-graphc/src/main/java/com/fksm/web/service/common/GraphcService.java
// Path: common/src/main/java/com/fksm/common/dto/CallersStatics.java // public class CallersStatics implements Comparable { // private Long time; // private Map<String, Integer> callers; // // public CallersStatics() { // } // // public CallersStatics(Long time, Map<String, Integer> callers) { // this.setTime(time); // this.setCallers(callers); // } // // public Long getTime() { // return time; // } // // public void setTime(Long time) { // this.time = time; // } // // public Map<String, Integer> getCallers() { // return callers; // } // // public void setCallers(Map<String, Integer> callers) { // this.callers = callers; // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof CallersStatics){ // CallersStatics info = (CallersStatics)obj; // return info.time == this.time ? true : false; // } // return super.equals(obj); // } // // public int compareTo(Object o) { // if (o instanceof CallersStatics){ // CallersStatics info = (CallersStatics)o; // if (info.time > this.time) // return 1; // else if (info.time < this.time) // return -1; // else // return 0; // } // return 0; // } // } // // Path: common/src/main/java/com/fksm/common/dto/CodeStatics.java // public class CodeStatics implements Comparable { // private Long time; // private Double score; // // public CodeStatics() { // } // // public CodeStatics(Long time, Double score) { // this.setTime(time); // this.setScore(score); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof CodeStatics){ // CodeStatics info = (CodeStatics)obj; // return info.getTime() == this.getTime() ? true : false; // } // return super.equals(obj); // } // // public int compareTo(Object o) { // if (o instanceof CodeStatics){ // CodeStatics info = (CodeStatics)o; // if (info.time > this.time) // return 1; // else if (info.time < this.time) // return -1; // else // return 0; // } // return 0; // } // // public Long getTime() { // return time; // } // // public void setTime(Long time) { // this.time = time; // } // // public Double getScore() { // return score; // } // // public void setScore(Double score) { // this.score = score; // } // } // // Path: common/src/main/java/com/fksm/common/dto/CostsStatics.java // public class CostsStatics implements Comparable { // private Long time; // private Long costs; // // public CostsStatics() { // } // // public CostsStatics(Long time, Long costs) { // this.setTime(time); // this.setCosts(costs); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof CostsStatics){ // CostsStatics info = (CostsStatics)obj; // return info.getTime() == this.getTime() ? true : false; // } // return super.equals(obj); // } // // public int compareTo(Object o) { // if (o instanceof CostsStatics){ // CostsStatics info = (CostsStatics)o; // if (info.time > this.time) // return 1; // else if (info.time < this.time) // return -1; // else // return 0; // } // return 0; // } // // public Long getTime() { // return time; // } // // public void setTime(Long time) { // this.time = time; // } // // public Long getCosts() { // return costs; // } // // public void setCosts(Long costs) { // this.costs = costs; // } // } // // Path: common/src/main/java/com/fksm/common/dto/RequestStatics.java // public class RequestStatics implements Comparable { // private Long time; // private Integer count; // // public RequestStatics() { // } // // public RequestStatics(Long time, Integer count) { // this.setTime(time); // this.setCount(count); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof RequestStatics){ // RequestStatics info = (RequestStatics)obj; // return info.getTime() == this.getTime() ? true : false; // } // return super.equals(obj); // } // // public int compareTo(Object o) { // if (o instanceof RequestStatics){ // RequestStatics info = (RequestStatics)o; // if (info.getTime() > this.getTime()) // return 1; // else if (info.getTime() < this.getTime()) // return -1; // else // return 0; // } // return 0; // } // // public Long getTime() { // return time; // } // // public void setTime(Long time) { // this.time = time; // } // // public Integer getCount() { // return count; // } // // public void setCount(Integer count) { // this.count = count; // } // }
import com.fksm.common.dto.CallersStatics; import com.fksm.common.dto.CodeStatics; import com.fksm.common.dto.CostsStatics; import com.fksm.common.dto.RequestStatics; import java.util.*;
package com.fksm.web.service.common; /** * Created by Administrator on 2016/5/7. */ public interface GraphcService { /** * getServerServices * @return * @throws Exception */ public Map<String, Set<String>> getServerServices() throws Exception;
// Path: common/src/main/java/com/fksm/common/dto/CallersStatics.java // public class CallersStatics implements Comparable { // private Long time; // private Map<String, Integer> callers; // // public CallersStatics() { // } // // public CallersStatics(Long time, Map<String, Integer> callers) { // this.setTime(time); // this.setCallers(callers); // } // // public Long getTime() { // return time; // } // // public void setTime(Long time) { // this.time = time; // } // // public Map<String, Integer> getCallers() { // return callers; // } // // public void setCallers(Map<String, Integer> callers) { // this.callers = callers; // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof CallersStatics){ // CallersStatics info = (CallersStatics)obj; // return info.time == this.time ? true : false; // } // return super.equals(obj); // } // // public int compareTo(Object o) { // if (o instanceof CallersStatics){ // CallersStatics info = (CallersStatics)o; // if (info.time > this.time) // return 1; // else if (info.time < this.time) // return -1; // else // return 0; // } // return 0; // } // } // // Path: common/src/main/java/com/fksm/common/dto/CodeStatics.java // public class CodeStatics implements Comparable { // private Long time; // private Double score; // // public CodeStatics() { // } // // public CodeStatics(Long time, Double score) { // this.setTime(time); // this.setScore(score); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof CodeStatics){ // CodeStatics info = (CodeStatics)obj; // return info.getTime() == this.getTime() ? true : false; // } // return super.equals(obj); // } // // public int compareTo(Object o) { // if (o instanceof CodeStatics){ // CodeStatics info = (CodeStatics)o; // if (info.time > this.time) // return 1; // else if (info.time < this.time) // return -1; // else // return 0; // } // return 0; // } // // public Long getTime() { // return time; // } // // public void setTime(Long time) { // this.time = time; // } // // public Double getScore() { // return score; // } // // public void setScore(Double score) { // this.score = score; // } // } // // Path: common/src/main/java/com/fksm/common/dto/CostsStatics.java // public class CostsStatics implements Comparable { // private Long time; // private Long costs; // // public CostsStatics() { // } // // public CostsStatics(Long time, Long costs) { // this.setTime(time); // this.setCosts(costs); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof CostsStatics){ // CostsStatics info = (CostsStatics)obj; // return info.getTime() == this.getTime() ? true : false; // } // return super.equals(obj); // } // // public int compareTo(Object o) { // if (o instanceof CostsStatics){ // CostsStatics info = (CostsStatics)o; // if (info.time > this.time) // return 1; // else if (info.time < this.time) // return -1; // else // return 0; // } // return 0; // } // // public Long getTime() { // return time; // } // // public void setTime(Long time) { // this.time = time; // } // // public Long getCosts() { // return costs; // } // // public void setCosts(Long costs) { // this.costs = costs; // } // } // // Path: common/src/main/java/com/fksm/common/dto/RequestStatics.java // public class RequestStatics implements Comparable { // private Long time; // private Integer count; // // public RequestStatics() { // } // // public RequestStatics(Long time, Integer count) { // this.setTime(time); // this.setCount(count); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof RequestStatics){ // RequestStatics info = (RequestStatics)obj; // return info.getTime() == this.getTime() ? true : false; // } // return super.equals(obj); // } // // public int compareTo(Object o) { // if (o instanceof RequestStatics){ // RequestStatics info = (RequestStatics)o; // if (info.getTime() > this.getTime()) // return 1; // else if (info.getTime() < this.getTime()) // return -1; // else // return 0; // } // return 0; // } // // public Long getTime() { // return time; // } // // public void setTime(Long time) { // this.time = time; // } // // public Integer getCount() { // return count; // } // // public void setCount(Integer count) { // this.count = count; // } // } // Path: web-graphc/src/main/java/com/fksm/web/service/common/GraphcService.java import com.fksm.common.dto.CallersStatics; import com.fksm.common.dto.CodeStatics; import com.fksm.common.dto.CostsStatics; import com.fksm.common.dto.RequestStatics; import java.util.*; package com.fksm.web.service.common; /** * Created by Administrator on 2016/5/7. */ public interface GraphcService { /** * getServerServices * @return * @throws Exception */ public Map<String, Set<String>> getServerServices() throws Exception;
public List<CallersStatics> getServerServiceCallers(String serverIp, String serviceId) throws Exception;
wuzhongdehua/fksm
web-graphc/src/main/java/com/fksm/web/service/common/GraphcService.java
// Path: common/src/main/java/com/fksm/common/dto/CallersStatics.java // public class CallersStatics implements Comparable { // private Long time; // private Map<String, Integer> callers; // // public CallersStatics() { // } // // public CallersStatics(Long time, Map<String, Integer> callers) { // this.setTime(time); // this.setCallers(callers); // } // // public Long getTime() { // return time; // } // // public void setTime(Long time) { // this.time = time; // } // // public Map<String, Integer> getCallers() { // return callers; // } // // public void setCallers(Map<String, Integer> callers) { // this.callers = callers; // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof CallersStatics){ // CallersStatics info = (CallersStatics)obj; // return info.time == this.time ? true : false; // } // return super.equals(obj); // } // // public int compareTo(Object o) { // if (o instanceof CallersStatics){ // CallersStatics info = (CallersStatics)o; // if (info.time > this.time) // return 1; // else if (info.time < this.time) // return -1; // else // return 0; // } // return 0; // } // } // // Path: common/src/main/java/com/fksm/common/dto/CodeStatics.java // public class CodeStatics implements Comparable { // private Long time; // private Double score; // // public CodeStatics() { // } // // public CodeStatics(Long time, Double score) { // this.setTime(time); // this.setScore(score); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof CodeStatics){ // CodeStatics info = (CodeStatics)obj; // return info.getTime() == this.getTime() ? true : false; // } // return super.equals(obj); // } // // public int compareTo(Object o) { // if (o instanceof CodeStatics){ // CodeStatics info = (CodeStatics)o; // if (info.time > this.time) // return 1; // else if (info.time < this.time) // return -1; // else // return 0; // } // return 0; // } // // public Long getTime() { // return time; // } // // public void setTime(Long time) { // this.time = time; // } // // public Double getScore() { // return score; // } // // public void setScore(Double score) { // this.score = score; // } // } // // Path: common/src/main/java/com/fksm/common/dto/CostsStatics.java // public class CostsStatics implements Comparable { // private Long time; // private Long costs; // // public CostsStatics() { // } // // public CostsStatics(Long time, Long costs) { // this.setTime(time); // this.setCosts(costs); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof CostsStatics){ // CostsStatics info = (CostsStatics)obj; // return info.getTime() == this.getTime() ? true : false; // } // return super.equals(obj); // } // // public int compareTo(Object o) { // if (o instanceof CostsStatics){ // CostsStatics info = (CostsStatics)o; // if (info.time > this.time) // return 1; // else if (info.time < this.time) // return -1; // else // return 0; // } // return 0; // } // // public Long getTime() { // return time; // } // // public void setTime(Long time) { // this.time = time; // } // // public Long getCosts() { // return costs; // } // // public void setCosts(Long costs) { // this.costs = costs; // } // } // // Path: common/src/main/java/com/fksm/common/dto/RequestStatics.java // public class RequestStatics implements Comparable { // private Long time; // private Integer count; // // public RequestStatics() { // } // // public RequestStatics(Long time, Integer count) { // this.setTime(time); // this.setCount(count); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof RequestStatics){ // RequestStatics info = (RequestStatics)obj; // return info.getTime() == this.getTime() ? true : false; // } // return super.equals(obj); // } // // public int compareTo(Object o) { // if (o instanceof RequestStatics){ // RequestStatics info = (RequestStatics)o; // if (info.getTime() > this.getTime()) // return 1; // else if (info.getTime() < this.getTime()) // return -1; // else // return 0; // } // return 0; // } // // public Long getTime() { // return time; // } // // public void setTime(Long time) { // this.time = time; // } // // public Integer getCount() { // return count; // } // // public void setCount(Integer count) { // this.count = count; // } // }
import com.fksm.common.dto.CallersStatics; import com.fksm.common.dto.CodeStatics; import com.fksm.common.dto.CostsStatics; import com.fksm.common.dto.RequestStatics; import java.util.*;
package com.fksm.web.service.common; /** * Created by Administrator on 2016/5/7. */ public interface GraphcService { /** * getServerServices * @return * @throws Exception */ public Map<String, Set<String>> getServerServices() throws Exception; public List<CallersStatics> getServerServiceCallers(String serverIp, String serviceId) throws Exception;
// Path: common/src/main/java/com/fksm/common/dto/CallersStatics.java // public class CallersStatics implements Comparable { // private Long time; // private Map<String, Integer> callers; // // public CallersStatics() { // } // // public CallersStatics(Long time, Map<String, Integer> callers) { // this.setTime(time); // this.setCallers(callers); // } // // public Long getTime() { // return time; // } // // public void setTime(Long time) { // this.time = time; // } // // public Map<String, Integer> getCallers() { // return callers; // } // // public void setCallers(Map<String, Integer> callers) { // this.callers = callers; // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof CallersStatics){ // CallersStatics info = (CallersStatics)obj; // return info.time == this.time ? true : false; // } // return super.equals(obj); // } // // public int compareTo(Object o) { // if (o instanceof CallersStatics){ // CallersStatics info = (CallersStatics)o; // if (info.time > this.time) // return 1; // else if (info.time < this.time) // return -1; // else // return 0; // } // return 0; // } // } // // Path: common/src/main/java/com/fksm/common/dto/CodeStatics.java // public class CodeStatics implements Comparable { // private Long time; // private Double score; // // public CodeStatics() { // } // // public CodeStatics(Long time, Double score) { // this.setTime(time); // this.setScore(score); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof CodeStatics){ // CodeStatics info = (CodeStatics)obj; // return info.getTime() == this.getTime() ? true : false; // } // return super.equals(obj); // } // // public int compareTo(Object o) { // if (o instanceof CodeStatics){ // CodeStatics info = (CodeStatics)o; // if (info.time > this.time) // return 1; // else if (info.time < this.time) // return -1; // else // return 0; // } // return 0; // } // // public Long getTime() { // return time; // } // // public void setTime(Long time) { // this.time = time; // } // // public Double getScore() { // return score; // } // // public void setScore(Double score) { // this.score = score; // } // } // // Path: common/src/main/java/com/fksm/common/dto/CostsStatics.java // public class CostsStatics implements Comparable { // private Long time; // private Long costs; // // public CostsStatics() { // } // // public CostsStatics(Long time, Long costs) { // this.setTime(time); // this.setCosts(costs); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof CostsStatics){ // CostsStatics info = (CostsStatics)obj; // return info.getTime() == this.getTime() ? true : false; // } // return super.equals(obj); // } // // public int compareTo(Object o) { // if (o instanceof CostsStatics){ // CostsStatics info = (CostsStatics)o; // if (info.time > this.time) // return 1; // else if (info.time < this.time) // return -1; // else // return 0; // } // return 0; // } // // public Long getTime() { // return time; // } // // public void setTime(Long time) { // this.time = time; // } // // public Long getCosts() { // return costs; // } // // public void setCosts(Long costs) { // this.costs = costs; // } // } // // Path: common/src/main/java/com/fksm/common/dto/RequestStatics.java // public class RequestStatics implements Comparable { // private Long time; // private Integer count; // // public RequestStatics() { // } // // public RequestStatics(Long time, Integer count) { // this.setTime(time); // this.setCount(count); // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof RequestStatics){ // RequestStatics info = (RequestStatics)obj; // return info.getTime() == this.getTime() ? true : false; // } // return super.equals(obj); // } // // public int compareTo(Object o) { // if (o instanceof RequestStatics){ // RequestStatics info = (RequestStatics)o; // if (info.getTime() > this.getTime()) // return 1; // else if (info.getTime() < this.getTime()) // return -1; // else // return 0; // } // return 0; // } // // public Long getTime() { // return time; // } // // public void setTime(Long time) { // this.time = time; // } // // public Integer getCount() { // return count; // } // // public void setCount(Integer count) { // this.count = count; // } // } // Path: web-graphc/src/main/java/com/fksm/web/service/common/GraphcService.java import com.fksm.common.dto.CallersStatics; import com.fksm.common.dto.CodeStatics; import com.fksm.common.dto.CostsStatics; import com.fksm.common.dto.RequestStatics; import java.util.*; package com.fksm.web.service.common; /** * Created by Administrator on 2016/5/7. */ public interface GraphcService { /** * getServerServices * @return * @throws Exception */ public Map<String, Set<String>> getServerServices() throws Exception; public List<CallersStatics> getServerServiceCallers(String serverIp, String serviceId) throws Exception;
public List<CodeStatics> getServerServiceCodes(String serverIp, String serviceId) throws Exception;
wuzhongdehua/fksm
web-graphc/src/main/java/com/fksm/web/service/common/impl/DemoServiceImpl.java
// Path: common/src/main/java/com/fksm/common/util/Constants.java // public class Constants { // /** The Constant REGEX. */ // public static final String REGEX_UUID = "regex.uuid"; // public static final String REGEX_IP = "regex.ip"; // public static final String REGEX_TIME = "regex.time"; // // public static final int TYPE_CALLER_INFO = 1; // public static final int TYPE_RESP_PARAM = 2; // public static final int TYPE_REQ_PARAM = 3; // public static final int TYPE_RESP_TIME = 4; // public static final int TYPE_SERVICE_INFO = 5; // // public static final String REDIS_SERVER_KEY = "SERVER"; // // public static final String REDIS_SERVER_SERVICE_PREFIX = "SERVER_SERVICE_"; // public static final String REDIS_SERVICE_REQUEST_PREFIX = "SERVICE_REQUEST_"; // public static final String REDIS_TIME_REQUESTS_PREFIX = "TIME_REQUESTS_"; // //server->service->requests // public static final String REDIS_SERVER_SERVICE_REQUEST_PREFIX = "SERVER_SERVICE_REQUEST_"; // // public static final String REDIS_SERVICE_COSTS_PREFIX = "SERVICE_COSTS_"; // public static final String REDIS_SERVICE_CALLERS_PREFIX = "SERVICE_CALLERS_"; // public static final String REDIS_SERVICE_CODES_PREFIX = "SERVICE_CODES_"; // // public static final String REDIS_SERVICE_REQUEST_CALLER_PREFIX = "SERVICE_REQUEST_CALLER_"; // public static final String REDIS_SERVER_SERVICE_COST_PREFIX = "SERVER_SERVICE_COST_"; // public static final String REDIS_SERVICE_REQUEST_CODE_PREFIX = "SERVICE_REQUEST_CODE_"; // // public static final String REDIS_SERVER_PREFIX = "S_SERVER_SERVICE_REQUEST_"; // public static final String REDIS_SERVER_COSTS_PREFIX = "S_SERVER_SERVICE_COSTS_"; // public static final String REDIS_SERVER_CALLER_PREFIX = "S_SERVER_SERVICE_CALLER_"; // public static final String REDIS_SERVER_CODE_PREFIX = "S_SERVER_SERVICE_CODE_"; // // public static final String REDIS_TIMELINE_KEY = "TIMELINE_KEY"; // // public static final Integer CODE_SUCESS = 100; // } // // Path: web-graphc/src/main/java/com/fksm/web/service/common/DemoService.java // public interface DemoService { // /** // * getCallers // * @return // * @throws Exception // */ // public List<HashMap> getCallers(Long startTime, Long endTime, String server_ip, String service_id) throws Exception; // }
import com.alibaba.fastjson.JSON; import com.fksm.common.util.Constants; import com.fksm.web.service.common.DemoService; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.ZSetOperations.*; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.*;
package com.fksm.web.service.common.impl; /** * Created by Administrator on 2016/5/7. */ @Service("demoService") public class DemoServiceImpl implements DemoService { @Resource(name = "redisTemplate") private RedisTemplate<String, String> redisTemplate; @Override public List<HashMap> getCallers(Long startTime, Long endTime, String server_ip, String service_id) throws Exception {
// Path: common/src/main/java/com/fksm/common/util/Constants.java // public class Constants { // /** The Constant REGEX. */ // public static final String REGEX_UUID = "regex.uuid"; // public static final String REGEX_IP = "regex.ip"; // public static final String REGEX_TIME = "regex.time"; // // public static final int TYPE_CALLER_INFO = 1; // public static final int TYPE_RESP_PARAM = 2; // public static final int TYPE_REQ_PARAM = 3; // public static final int TYPE_RESP_TIME = 4; // public static final int TYPE_SERVICE_INFO = 5; // // public static final String REDIS_SERVER_KEY = "SERVER"; // // public static final String REDIS_SERVER_SERVICE_PREFIX = "SERVER_SERVICE_"; // public static final String REDIS_SERVICE_REQUEST_PREFIX = "SERVICE_REQUEST_"; // public static final String REDIS_TIME_REQUESTS_PREFIX = "TIME_REQUESTS_"; // //server->service->requests // public static final String REDIS_SERVER_SERVICE_REQUEST_PREFIX = "SERVER_SERVICE_REQUEST_"; // // public static final String REDIS_SERVICE_COSTS_PREFIX = "SERVICE_COSTS_"; // public static final String REDIS_SERVICE_CALLERS_PREFIX = "SERVICE_CALLERS_"; // public static final String REDIS_SERVICE_CODES_PREFIX = "SERVICE_CODES_"; // // public static final String REDIS_SERVICE_REQUEST_CALLER_PREFIX = "SERVICE_REQUEST_CALLER_"; // public static final String REDIS_SERVER_SERVICE_COST_PREFIX = "SERVER_SERVICE_COST_"; // public static final String REDIS_SERVICE_REQUEST_CODE_PREFIX = "SERVICE_REQUEST_CODE_"; // // public static final String REDIS_SERVER_PREFIX = "S_SERVER_SERVICE_REQUEST_"; // public static final String REDIS_SERVER_COSTS_PREFIX = "S_SERVER_SERVICE_COSTS_"; // public static final String REDIS_SERVER_CALLER_PREFIX = "S_SERVER_SERVICE_CALLER_"; // public static final String REDIS_SERVER_CODE_PREFIX = "S_SERVER_SERVICE_CODE_"; // // public static final String REDIS_TIMELINE_KEY = "TIMELINE_KEY"; // // public static final Integer CODE_SUCESS = 100; // } // // Path: web-graphc/src/main/java/com/fksm/web/service/common/DemoService.java // public interface DemoService { // /** // * getCallers // * @return // * @throws Exception // */ // public List<HashMap> getCallers(Long startTime, Long endTime, String server_ip, String service_id) throws Exception; // } // Path: web-graphc/src/main/java/com/fksm/web/service/common/impl/DemoServiceImpl.java import com.alibaba.fastjson.JSON; import com.fksm.common.util.Constants; import com.fksm.web.service.common.DemoService; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.ZSetOperations.*; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.*; package com.fksm.web.service.common.impl; /** * Created by Administrator on 2016/5/7. */ @Service("demoService") public class DemoServiceImpl implements DemoService { @Resource(name = "redisTemplate") private RedisTemplate<String, String> redisTemplate; @Override public List<HashMap> getCallers(Long startTime, Long endTime, String server_ip, String service_id) throws Exception {
String k = Constants.REDIS_SERVER_CALLER_PREFIX + server_ip + "_" + service_id;