001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.juneau.marshall.swaps;
018
019import static org.apache.juneau.commons.utils.Shorts.*;
020
021import java.util.*;
022
023import org.apache.juneau.marshall.*;
024import org.apache.juneau.marshall.swap.spi.*;
025
026/**
027 * Transforms {@link StackTraceElement StackTraceElements} to {@code String} objects.
028 *
029 * <p>
030 * The swap is identical to just calling {@link StackTraceElement#toString()}, but provides the ability to
031 * parse the resulting string back into a bean.
032 *
033 * <h5 class='section'>See Also:</h5><ul>
034 *    <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/Swaps">Swap</a>
035
036 * </ul>
037 */
038public class StackTraceElementSwap extends ObjectSwap<StackTraceElement,String> {
039
040   /**
041    * Converts the specified {@link Enumeration} to a {@link List}.
042    */
043   @Override /* Overridden from ObjectSwap */
044   public String swap(MarshallingSession session, StackTraceElement o) {
045      return o.toString();
046   }
047
048   @Override /* Overridden from ObjectSwap */
049   public StackTraceElement unswap(MarshallingSession session, String in, ClassMeta<?> hint) {
050      var methodName = "";
051      String fileName = null;
052      int lineNumber = -1;
053
054      if (in == null)
055         return null;
056
057      var i = in.indexOf('(');
058      if (i != -1) {
059         var s = in.substring(i + 1, in.lastIndexOf(')'));
060         in = in.substring(0, i);
061         i = s.indexOf(':');
062         if (i != -1) {
063            fileName = s.substring(0, i);
064            lineNumber = Integer.parseInt(s.substring(i + 1));
065         } else if (eq(s, "Native Method")) {
066            lineNumber = -2;
067         } else if (neq(s, "Unknown Source")) {
068            fileName = s;
069         }
070      }
071
072      i = in.lastIndexOf('.');
073      if (i != -1) {
074         methodName = in.substring(i + 1);
075         in = in.substring(0, i);
076      }
077
078      return new StackTraceElement(in, methodName, fileName, lineNumber);
079   }
080}